Managing State in React
Making your components dynamic and interactive.
State is a JavaScript object that stores a component's dynamic data and determines how the component renders and behaves. State allows components to create and manage their own data. When the state of a component changes, React re-renders the component to reflect these changes in the UI.
Using the `useState` Hook
In function components, the `useState` Hook is the primary way to add state. It returns an array with two values: the current state and a function to update it.
import { useState } from 'react';
function Counter() {
// Declare a new state variable, which we'll call "count"
// useState(0) means the initial state for count is 0
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}Live Counter Example:
You clicked 0 times
Key Principles of State:
- Do Not Modify State Directly: Always use the updater function (e.g., `setCount`) to change state. Direct modification (e.g., `count = count + 1`) will not trigger a re-render.
- State Updates May Be Asynchronous: React may batch multiple state updates for performance. Don't rely on the state value being updated immediately after calling the updater function. If you need to use the previous state to calculate the new state, use the functional update form: `setCount(prevCount => prevCount + 1)`.
- State is Local: State is typically local to the component where it's defined. To share state between components, you often "lift state up" to their closest common ancestor.
Test Your Knowledge
Question 1/3
What is 'state' in the context of a React component?