Introduction:
In the previous article, we covered the useReducer hook and learned how it can be used to manage complex state in React applications. In this article, we will explore another important hook - the useState hook - and see how it can be used to manage simple state updates in your components.
What is useState:
The useState hook is used to add state to your functional components. It takes an initial state as an argument and returns an array with two values: the current state and a setter function that can be used to update the state.
Example:
Let's look at a simple example to see how useState works. We'll create a component that displays a count and a button that increments the count when clicked.
Code:
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
Explanation:
In this example, we use the useState hook and pass it the initial state, which is 0. The hook returns an array with two values: the current state and the setter function. We use the current state to display the count and the setter function to update the state when the button is clicked.
In the onClick event handler for the button, we call the setter function and pass it the new count value, which is the current count plus one. This updates the state and re-renders the component with the updated count.
Conclusion:
The useState hook is a simple and easy-to-use tool for adding state to your functional components. It's a great tool for managing simple state updates in your components. In this tutorial, we've looked at a simple example of how to use the useState hook to create a counter component that displays a count and increments the count when a button is clicked. If you have any questions, feel free to ask in the comments below.
Top comments (0)