What is useState? How does it work?

In React, useState is a Hook that allows you to add state to functional components. Essentially, it's a way to make functional components "remember" values between renders. Here's a breakdown :

What is State?

  • In React, "state" refers to data that can change over time within a component.
  • When state changes, React re-renders the component to reflect those changes in the UI.

How useState Works:

  1. Declaration:

    • You import useState from the react library.
    • Inside your functional component, you call useState with an initial value.
    • useState returns an array with two elements:
      • The current state value.
      • A function that allows you to update the state value.
  2. Using the State:

    • You can use the current state value in your component's JSX to display dynamic data.
    • When you need to update the state, you call the update function provided by useState.
  3. Re-renders:

    • When you call the update function, React schedules a re-render of the component.
    • During the re-render, React updates the state value and updates the UI accordingly.

Key Concepts:

  • Initial State:
    • The argument you pass to useState is the initial value of the state.
    • This value is only used during the first render of the component.
  • State Update Function:
    • The function returned by useState is used to update the state.
    • When updating state, it's best practice to use functional updates, especially when the new state depends on the previous state.
  • Re-renders:
    • React re-renders the component whenever the state is updated.
    • This ensures that the UI always reflects the current state.

Example :

import React, { useState } from 'react';

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

export default Counter;

In this example :  

* useState(0) initializes the count state to 0.
* setCount is the function used to update the count value.
* When the button is clicked, setCount(count + 1) increments the count and triggers a re-render.

useState is a fundamental Hook in React that simplifies state management in functional components.