reactjs
  1. reactjs-what-is-the-usestate-in-react

ReactJs - What is the useState Hook?

ReactJs is a JavaScript library that is used for building user interfaces. It provides various Hooks to manage the state of the components.

In this tutorial, we will learn about the useState Hook in ReactJs.

Heading h1

ReactJs - What is the useState Hook?

Syntax

const [state, setState] = useState(initialState);

Example

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

Output

useState Hook Example Output

Explanation

The useState Hook is a function that returns a pair of values such as state and setState. The state is the current state of the component and the setState is a function used to update the state.

In the above example, we have used the useState Hook to manage the count state of a counter. Initially, the count is set to 0. When the Click me button is clicked, the setCount function updates the count state and triggers a re-render of the component.

Use

The useState Hook is used to manage the state of the functional components in ReactJs.

Important Points

  • The useState Hook is a function that returns a pair of values such as state and setState.
  • The initial state is passed as an argument to the useState function.
  • The setState function triggers a re-render of the component when the state is updated.
  • The useState Hook can be used multiple times in a single component to manage multiple states.

Summary

In this tutorial, we have learned about the useState Hook in ReactJs, how to use it to manage state in functional components, and its important points.

Published on: