19 Feb 2024
The useState hook in React enables functional components to manage state variables. It allows you to define and modify state within functional components. This hook returns an array containing the current state value and a function to update the state.
Here's an overview of how useState works:
-
Initialization: When you call
useStatewith an initial value, React sets up the initial state of your component. This is typically done during the initial render.const [state, setState] = useState(initialValue);The
statevariable represents the current state value, andsetStateis a function that you can use to update the state. -
Rendering: React renders the component, and during the render, the
statevariable holds the current value of the state. You can use this value within your component's JSX to render the UI based on the current state.return <div>{state}</div>; -
Updating State: When you want to update the state, you call the
setStatefunction. This triggers a re-render of the component with the updated state.setState(newValue);Alternatively, you can use a functional update to update the state based on the previous state value.
setState((prevState) => prevState + 1);The functional update is particularly useful when the new state value depends on the previous state.
-
Re-rendering: After calling
setState, React schedules a re-render of the component. During the re-render, the component's function body is executed again, and thestatevariable now holds the updated state value.React efficiently updates the DOM to reflect the changes in state, ensuring that only the necessary parts of the UI are re-rendered.
-
Persistent Identity: The identity of the
setStatefunction returned byuseStateremains constant throughout the component's lifetime. This property is important for React to correctly associate the state updates with the corresponding state variable. -
Batching Updates: React batches multiple state updates that occur within the same synchronous event (e.g., a button click or an API response) into a single re-render. This helps improve performance by reducing unnecessary re-renders.
-
Asynchronous Nature: While state updates are asynchronous, React guarantees that the updated state is applied before the next paint. This means that if you read the state immediately after calling
setState, you'll get the updated value.