In React, State is a private, built-in object within a component that is used to store data that changes over time and affects the component’s output. When a component’s state changes, React automatically re-renders the component and updates the DOM, ensuring the UI always reflects the latest data.
State provides the dynamic behavior needed for interactivity, such as tracking button clicks, managing input values, or loading external data.
1. The useState Hook
In functional components, you cannot simply define a variable like $count = 0; because that variable would be lost every time the function re-renders. The useState Hook solves this by providing a way for functional components to manage and preserve their state across re-renders.
The useState Hook returns an array containing exactly two elements:
- The current state value (e.g.,
count). - A function to update the state (e.g.,
setCount).
Syntax:
const [stateVariable, setStateFunction] = useState(initialValue);
2. Execution Example: Creating Interactive State
Let’s build a simple counter component to demonstrate how useState works to manage and update dynamic data.
In your my-first-app/src directory:
- Open the main file,
App.js. - Replace its content with the following code:
import React, { useState } from 'react';
function Counter() {
// 1. Initialize State using the useState Hook
// 'count' is the current state value, initialized to 0.
// 'setCount' is the function used to update the 'count' value.
const [count, setCount] = useState(0);
// 2. Event handler function to update state
const incrementCount = () => {
// The setStateFunction (setCount) tells React to update the state.
// This triggers an automatic re-render of the component.
setCount(count + 1);
};
// 3. Event handler to decrement state
const decrementCount = () => {
// State can be updated based on any logic
if (count > 0) {
setCount(count - 1);
}
};
return (
<div className="Counter">
<h1>Simple Counter Application</h1>
{/* 4. Display the current state value */}
<p>Current Count: <strong>{count}</strong></p>
{/* 5. Attach handlers to modify state */}
<button onClick={incrementCount}>
Increment (+)
</button>
<button onClick={decrementCount} style={{ marginLeft: '10px' }}>
Decrement (-)
</button>
</div>
);
}
export default Counter;
- Local Execution: Run
npm startin your project’s terminal. - Observation: Clicking the “Increment” button updates the
countstate. React detects this change, calls theCounterfunction again with the newcountvalue, and updates the display.
3. Updating State Based on Previous State (Best Practice)
In asynchronous or concurrent operations, relying directly on the current count value (setCount(count + 1)) can sometimes lead to stale data.
The robust best practice is to pass a function to the state updater. This function receives the previous state as its argument, guaranteeing you are working with the most up-to-date value.
Example of Functional Update (Guaranteed Correctness):
// Safely incrementing state using the previous value (prevCount)
const incrementSafely = () => {
setCount(prevCount => prevCount + 1);
};
This pattern should be used whenever the new state depends on the old state.
