Welcome to our deep dive into useState! Today, we're going to learn about this powerful feature in React JS that allows us to manage state in our components. 📝 Note: State is a data that can change over time, and React uses it to re-render components when data changes.
useState is a built-in hook (function) in React that lets us create, initialize, and manage state variables. It's a function that returns an array with two values: the current state and a function to update it.
import React, { useState } from 'react';
function Example() {
// Declare a state variable called count
const [count, setCount] = useState(0);
return (
<div>
Count: {count}
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}In the example above, we've created a state variable count initialized to 0. We've also created a button that increments the count when clicked. 💡 Pro Tip: Always name your state variables descriptively, making your code easier to understand.
To update a state variable, we use the function returned by useState. This function takes a new state value as an argument and updates the state variable.
import React, { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
return (
<div>
Count: {count}
<button onClick={() => setCount(count + 1)}>
Increment
</button>
<button onClick={() => setCount(0)}>
Reset
</button>
</div>
);
}In this example, we've added a button to reset the count to 0. 📝 Note: Never modify state directly. Always use the function returned by useState to update state.
Updating state directly can lead to unintended side effects, like causing multiple re-renders. To avoid this, always use the function returned by useState to update state.
import React, { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
const incrementCount = () => {
setCount(count + 1);
};
return (
<div>
Count: {count}
<button onClick={incrementCount}>
Increment
</button>
</div>
);
}In this example, we've created a separate function incrementCount to increment the count, avoiding potential side effects.
Sometimes, we might want to update state based on the current state. In such cases, we use what's called a "functional update." This involves passing a function to setCount that calculates the new state based on the current state.
import React, { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
const incrementCount = () => {
setCount(count + 1);
};
const resetCount = () => {
setCount(0);
};
return (
<div>
Count: {count}
<button onClick={incrementCount}>Increment</button>
<button onClick={resetCount}>Reset</button>
</div>
);
}In this example, we've created a function resetCount to reset the count to 0.
Create a component that maintains the state of a user's name and an input field to update it.
Create a component that maintains the state of a list of items and a form to add new items.
Why should we never modify state directly in React?