React's useState hook is a fundamental API for React function components, enabling you to add state. When you call useState, it returns two values: the current state and a function to update it. When you call this update function, React schedules the new state value into the update queue and triggers a re-render of the component.
Here's a basic usage example of useState:
jsximport React, { useState } from 'react'; function Example() { // Declare a new state variable, which we call 'count' const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }
In the above example, every time the button is clicked, the setCount function is called with count + 1 as the new state value. This is how re-rendering is triggered:
- Call the state update function: When
setCountis invoked, React records the new state value (count + 1). - Schedule an update: React schedules this state update task into its internal update queue.
- Re-render the component: React initiates the re-rendering process. During this process, it uses the updated state to call the function component, obtain the latest JSX, and compare it with the previous render result (a process known as "reconciliation").
- DOM Update: If the new JSX differs from the previous render, React updates the DOM to match the new JSX.
This process ensures that the component updates its output in response to state changes, achieving a responsive UI. Since useState is designed to be responsive, it only triggers a re-render when the state actually changes. If you call the update function with the same state value, React treats the state as unchanged and may not trigger a re-render.