React useState in Brief | With Example
Subhash Kumar

Software Developer, educator & CEO Dot Simplify

React useState in Brief | With Example

useState is a hook in React that adds state to functional components. Before the introduction of hooks, only class components could have state. With the useState hook, you can add state to functional components and manage state updates. Here's an example of how to use the useState hook in a functional component:

import React, { useState } from 'react';

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

  return (
    
You clicked {count} times
 setCount(count + 1)}>
        Click me
      

  );
}

In the example above, we have a functional component called Example that has a state variable called count. The useState hook takes one argument, which is the initial state. In this case, the initial state is 0. The useState hook returns an array with two elements: the current state value and a function to update the state. In the example above, we destructured the returned array into two variables: count and setCount. The count variable is the current value of the state, and the setCount function is used to update the state. In the example above, we passed count + 1 to the setCount function inside the onClick handler of the button. This will update the count state variable every time the button is clicked. It's important to note that the setCount function does not directly modify the count state variable. Instead, it schedules an update to the component, which will happen asynchronously. This is important because it ensures that the component always has the latest state, even if the state updates are happening in an unpredictable order. You can use the useState hook multiple times in a single component to have multiple pieces of state. Here's an example of a component with two state variables, count and name:


import React, { useState } from 'react';

function Example() {
  // Declare two state variables, which we'll call "count" and "name"
  const [count, setCount] = useState(0);
  const [name, setName] = useState('Alice');

  return (
    
You clicked {count} times
 setCount(count + 1)}>
        Click me
      
Your name is {name}
 setName('Bob')}>
        Change name
      

  );
}



In the example above, we have two state variables: count and name. Each state variable has its own setter function: setCount and setName. It's important to note that the state variables in a component should be independent of each other. In other words, the value of one state variable should not depend on the value of another state variable. If you need to have a state variable that depends on another state variable, you should use the useEffect hook, which allows you to perform side effects in a component based on