The useState hook in React is a way to manage state within a functional component. Prior to the introduction of hooks, managing state within a functional component required the use of a class component. With the useState hook, functional components have the ability to maintain their own state, making them more versatile and easier to work with.
How to implement useState?
The useState hook takes an initial value as its argument and returns an array containing the current state and a setter function for that state.
Examples of useState
The state can be set in different variables, as shown in the following example:
import { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
const [name, setName] = useState("John Doe");
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<p>Name: {name}</p>
<button onClick={() => setName("Jane Smith")}>Change Name</button>
</div>
);
}
In the above example, we have defined two state variables: count and name, and two corresponding setter functions: setCount and setName. The component renders a button to increment the count and another button to change the name.
In the second example, we will see the useState hook with an object:
import { useState } from 'react';
function Example() {
const [state, setState] = useState({
count: 0,
name: "John Doe"
});
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => setState({...state, count: state.count + 1})}>Increment</button>
<p>Name: {state.name}</p>
<button onClick={() => setState({...state, name: "Jane Smith"})}>Change Name</button>
</div>
);
}
In the above example, we have defined one variable called state, that is an object containing properties count and name, and one setState function. The component renders a button to increment the count and another button to change the name. Notice that in this example we are using the spread operator ... to keep the other state properties unchanged when updating only one property.
Conclusion
In summary, the useState hook in React allows functional components to maintain their own state, providing a more versatile and easier-to-work-with alternative to class components. It takes an initial value as its argument and returns an array containing the current state and a setter function for that state.