useState

All about useState hook in React


React hook to keep track and store immutable data within your components. A global variable within the scope of a component.

If multiple updates (of a state) happens in a single pass render, these updates are batched thus re-rendering the component once.

Notes:

Batching refers to the process of queuing up state updates and re-renders to be executed in a single batch, rather than executing them one by one.

const [state, setState] = useState(initialState);
Parameters
  • initialState - initial value of any type (boolean, array, integer, string, object).
Returns

useState() returns an array with two values:

  1. current state value. The first re-render will match initialState.
  2. a setter function
Use Cases
  • Stores form input values
  • Toggles buttons
  • Manages any other stateful data.
  • Any update in the state will re-render the component with the new state, ensuring the UI stays in sync with the data.
import React, { useState } from 'react';
 
function Counter() {
  const [count, setCount] = useState(0); // defining State
 
  const increment = () => {
    setCount(count + 1);
  };
 
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
}