useState is a Hook in React that allows functional components to maintain local state. In previous versions of React, only class components could use state. The introduction of useState enables functional components to use state similarly to class components.
Basic Usage
Basic syntax is as follows:
javascriptconst [state, setState] = useState(initialState);
- The useState function takes the initial state as a parameter and returns two values: the current state (state) and the function to update the state (setState).
- initialState can be a fixed value or a function; if it's a function, its return value is used as the initial state.
- state is used to access the current state value within the component.
- setState is a function used to update the state. When the state is updated, the component re-renders.
Example
Suppose we are developing a simple counter application:
javascriptimport React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); // Initialize count state to 0 return ( <div> <p>Current count: {count}</p> <button onClick={() => setCount(count + 1)}>Increase</button> <button onClick={() => setCount(count - 1)}>Decrease</button> </div> ); }
In this example:
- We call
useState(0)to initialize thecountstate to 0. setCountis used to updatecount. Every time a button is clicked,setCountis called to increment or decrementcount.- Every time the state changes, React re-renders the
Countercomponent to reflect the latest count value.
How it Works
When setState is called, React schedules an update to re-render the component asynchronously. This means React re-renders the component by re-executing the component function in memory to obtain the latest JSX and comparing it with the previous JSX. If differences exist, React updates the DOM to match the latest rendered output.
Guaranteeing State Updates
In some cases, state updates may depend on the previous state. React guarantees that state updates are safe, even in asynchronous events or delayed responses, ensuring the latest state is available. For example, if we want to ensure the counter increment operation always bases on the latest state, we can write:
javascriptsetCount(prevCount => prevCount + 1);
Here, we pass a function to setCount instead of a fixed value. This function receives the previous state value prevCount as a parameter and returns the updated state.
In summary, useState provides functional components with the ability to maintain state, making component development more concise and intuitive.