⚛️ React Q10 / 113

What is useState hook?

AI-Powered Answer ✓ Answered

The `useState` hook is a fundamental feature in React that allows functional components to manage and persist state. Before hooks, state management was primarily a feature of class components. `useState` bridges this gap, enabling functional components to have their own internal, mutable state, making them more powerful and capable of handling dynamic user interfaces.

What is `useState`?

At its core, useState is a React Hook that lets you add state to functional components. It allows components to 'remember' things, making them interactive and dynamic. When the state changes, React re-renders the component to reflect the new state.

The hook returns an array with two elements: the current state value and a function to update that value. This pairing is crucial for managing reactive data within your components.

Syntax

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

state: The current value of the state. setState: A function that allows you to update the state. Calling this function will trigger a re-render of the component with the new state. initialState: The initial value for the state. This can be any valid JavaScript data type (number, string, boolean, object, array, null, etc.). It's only used during the initial render.

How it Works (Example)

jsx
import React, { useState } from 'react';

function Counter() {
  // Declare a state variable 'count' and its setter 'setCount'
  // Initialize 'count' to 0
  const [count, setCount] = useState(0);

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

export default Counter;

In this example, count starts at 0. When the button is clicked, setCount(count + 1) is called, which updates the count state. React then re-renders the Counter component, and the updated count value is displayed.

Key Characteristics

  • State Preservation: The state managed by useState is preserved across component re-renders.
  • Immutability: Always treat state as immutable. When updating objects or arrays, create new instances rather than directly modifying the existing state.
  • Asynchronous Updates: setState updates can sometimes be asynchronous. If you need to update state based on the previous state, use the functional update form: setCount(prevCount => prevCount + 1).
  • Multiple States: You can use useState multiple times in a single component to manage different pieces of state independently.

When to Use It

useState is ideal for managing any data within a functional component that needs to change over time and whose changes should trigger a re-render of the UI. This includes form inputs, toggle states, counter values, fetched data, and more.