React’s useState
hook is a built-in hook that allows you to add state to your functional components. State is a way to store and manage data that can change over time, such as user input, the current time, or the result of an API call.
useState
is a hook that takes one argument, an initial state value. It returns an array with two elements: the current state value, and a function to update it. The state value can be of any type, such as a string, number, object, or array.
Here’s an example of how you might use useState
in a component:
import { useState } from 'react';
function MyComponent() {
const [count, setCount] = useState(0);
return (
<>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</>
);
}
n this example, the component maintains an internal count that starts at 0, and updates it when the button is clicked. The setCount
function takes the new value of the state and merges it with the previous state.
It’s important to note that the setCount
function only merge updates with the previous state for the objects or arrays. for the primitive types, it will just replace the previous state with new value.
Another important thing to keep in mind is that when calling the setCount
function, React will re-render the component and its children to reflect the updated state. Because React uses a virtual DOM, this process is fast and efficient.
You can also use useState hook multiple times to handle multiple state values.
import { useState } from 'react';
function MyComponent() {
const [count, setCount] = useState(0);
const [text, setText] = useState('initial text');
return (
<>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<p>Text: {text}</p>
<input type='text' onChange={e => setText(e.target.value)}/>
</>
);
}
In this example, the component has two state values, one is counting how many times the button is clicked and the other is the text the user types in an input.
In summary, useState
is a powerful hook that allows you to add state to your functional components. It allows you to store and manage data that can change over time, which is essential for building interactive and dynamic user interfaces. useState
hook is easy to use, and allows you to handle multiple state values, making it a great tool for building scalable and maintainable applications.