The useState
hook is one of the most important hooks in React. It allows you to add state to functional components, making use of state much easier compared to class components. In this post, we'll take a look at what the useState
hook is, how it works, and some best practices when using it.
What is the useState Hook?
The useState
hook is a special function that lets you use state in React functional components. Calling useState
declares a new state variable for the component. It returns an array with 2 elements - the current state value, and a function to update it:
const [count, setCount] = useState(0);
You can name the state variable (count
) and update function (setCount
) anything you want. The only argument to useState
is the initial state.
Using State and Setter Function
Once you've declared state with useState
, you can use the state value anywhere in your component:
<p>You clicked {count} times</p>
To update the state, call the setter function returned from useState
:
<button onClick={() => setCount(count + 1)}>
Click
</button>
This is similar to this.setState
in a class component, except the update is asynchronous instead of immediately mutating state. Multiple calls to the setter during a single render will batch the updates together into one update.
Functional Updates
You can also pass a function to the setter function which receives the previous value:
setCount(prevCount => prevCount + 1);
This is useful for more complex state updates that depend on the previous value. Accessing the state directly during an update could result in stale values.
useState Tips
Here are some tips to keep in mind when using the useState
hook:
Only call
useState
at the top level of a componentFor complex state logic, use
useReducer
insteadPass a function to the setter to safely read the current state
To update objects/arrays, make copies before updating
Overall, useState
provides a simple way to add local state to React function components. Following some best practices will help avoid common pitfalls when using state.
Conclusion
The useState
hook enables powerful function-based components in React. It provides an intuitive API for declaring and updating the state.
Some key points to remember:
Import
useState
from ReactDeclare state variable and setter function
Read state in component, update with setter
Pass functions to the setter to update safely
Learning to use useState
effectively will level up your React skills. The flexibility of hooks makes function components quite capable.