React State Management
1. Local State
Local state is the state that is managed within a single component. It is used to store data that is specific to that component and does not need to be shared with other components. Local state is typically managed using the useState hook in functional components.
Example:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
In this example, the count state is managed locally within the Counter component.
2. Global State
Global state is the state that is shared across multiple components. It is used to store data that needs to be accessed and updated by different parts of the application. Global state is typically managed using state management libraries like Redux or the Context API.
Example using Context API:
import React, { createContext, useContext, useState } from 'react';
const UserContext = createContext();
function App() {
const [user, setUser] = useState({ name: 'Alice' });
return (
<UserContext.Provider value={user}>
<Profile />
</UserContext.Provider>
);
}
function Profile() {
const user = useContext(UserContext);
return <p>Logged in as: {user.name}</p>;
}
In this example, the user state is managed globally using the Context API and is accessible in the Profile component.
3. Derived State
Derived state is the state that is computed from existing state or props. It is not stored as a separate state variable but is instead calculated on the fly when needed. Derived state is useful for keeping your state minimal and avoiding unnecessary re-renders.
Example:
import React, { useState } from 'react';
function Cart({ items }) {
const [quantity, setQuantity] = useState(1);
const totalPrice = items.reduce((sum, item) => sum + item.price * quantity, 0);
return (
<div>
<p>Total Price: ${totalPrice}</p>
<button onClick={() => setQuantity(quantity + 1)}>Add Quantity</button>
</div>
);
}
In this example, the totalPrice is derived from the items prop and the quantity state. It is recalculated whenever items or quantity changes.