In React, state represents data that changes over time. How and where you store it determines whether it’s local or global.
1️⃣ Local State
- Definition: State that is owned by a single component.
- Scope: Only accessible within the component that defines it.
- Use Cases: UI interactions, form inputs, toggles, modal visibility, etc.
- Example:
function Counter() {
const [count, setCount] = React.useState(0); // local state
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
Explanation:
countis specific to this Counter component- Other components cannot access it directly
2️⃣ Global State
- Definition: State that is shared across multiple components.
- Scope: Accessible anywhere in the app that subscribes to it.
- Use Cases: Authentication, user profile, theme, cart items, notifications.
- Example using Context API:
const UserContext = React.createContext();
function App() {
const [user, setUser] = React.useState({ name: "Alice" });
return (
<UserContext.Provider value={{ user, setUser }}>
<Header />
<Dashboard />
</UserContext.Provider>
);
}
function Header() {
const { user } = React.useContext(UserContext);
return <h1>Welcome, {user.name}</h1>;
}
Explanation:
userstate is accessible by multiple components (Header,Dashboard)- Ensures consistent state across the app
3️⃣ Key Differences
| Feature | Local State | Global State |
|---|---|---|
| Scope | Single component | Multiple components |
| Use Case | Component-specific UI | Shared data across app |
| Implementation | useState |
Context API, Redux, Zustand |
| Performance | Fast, limited re-renders | Can impact performance if overused |
| Complexity | Simple | More complex, needs planning |
⚡ In short:
Use local state for component-specific data, and global state when multiple components need to access or update the same data. Proper separation ensures performance and maintainability in React apps.