Search

React useState Hook

  • Share this:

The `useState` Hook is a built-in Hook in React that allows you to add state to functional components. It is a way to manage state in a functional component, without the need to convert it to a class component.

To use the `useState` Hook, you first need to import it from the `react` package. Then, you can call the `useState` function inside your functional component, and pass an initial state value as an argument. The `useState` function will return an array with two elements: the current state value, and a function that can be used to update the state value.

Here's an example of how to use the `useState` Hook in a functional component:

import { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

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

In this example, the initial state value for the `count` variable is 0. Every time the button is clicked, the `setCount` function is called with the new value for `count`, which updates the state and re-renders the component.

You can use the `useState` Hook multiple times in a single component to manage multiple pieces of state. For example:

import { useState } from 'react';

function Example() {
  // Declare two state variables: "count" and "name"
  const [count, setCount] = useState(0);
  const [name, setName] = useState('John');

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
      <p>Your name is {name}</p>
      <button onClick={() => setName('Jane')}>
        Change name
      </button>
    </div>
  );
}

I hope this helps! Let me know if you have any questions.

 

Tags:

About author
I am a professional web developer. I love programming and coding, and reading books. I am the founder and CEO of StorialTech.