React's useState
is a built-in hook that allows you to add state functionality to functional components. Prior to the introduction of hooks in React 16.8, class components were primarily used for state management. However, with the advent of hooks, state and other React features can now be leveraged in functional components, leading to cleaner, more readable code.
useState
is a function that takes the initial state as a parameter and returns an array that has two values:
Here is a sample syntax of using useState
:
const [state, setState] = useState(initialState);
In the above code:
state
represents the current state value which is initialized to initialState
.setState
is a function to update the state value.It's important to note that useState
doesn't merge the old and new state like this.setState
in class components. Instead, it replaces the old state. Therefore, you have to manually include the old state when updating if necessary.
A simple and practical example of useState
usage is in a counter application. In this scenario, the state
holds the current count value, and setState
changes the count value:
import React, { useState } from 'react';
function Counter() {
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, the count starts at 0 (useState(0)
). When the button is clicked, setCount
is invoked with the new count (count + 1
), updating the state, and consequently, the component re-renders.
Here are a few best practices when using useState
:
useState
can be used more than once in a single component.setState
like setCount(prevCount => prevCount + 1)
. This ensures that you always have the latest state value.By understanding the 'useState' hook in React, you can better manage state in functional components, leading to optimized, modular, and easily testable code.