Derived State in React.js: Improving State Management and Removing Redundancy & Dependency
Derived State in React.js: Improving State Management and Removing Redundancy & Dependency
Derived state is a concept in React that helps improve state management by eliminating redundant state variables and reducing dependency on unnecessary state updates. Instead of storing computed values in state, you derive them from existing state or props.
Why Use Derived State?
- Prevents unnecessary re-renders by avoiding redundant state variables.
- Improves maintainability and simplifies state updates.
- Reduces the risk of state inconsistency.
Example Code
import React, { useState } from "react";
function Cart() {
const [items, setItems] = useState([
{ id: 1, name: "Apple", price: 10, quantity: 2 },
{ id: 2, name: "Banana", price: 5, quantity: 3 }
]);
// Derived state: Calculate total price without storing it in state
const totalPrice = items.reduce((sum, item) => sum + item.price * item.quantity, 0);
return (
Shopping Cart
{items.map(item => (
{item.name} - ${item.price} x {item.quantity}
))}
Total Price: ${totalPrice}
);
}
Challenge: Improve Derived State
- Modify the code to add a discount feature that automatically calculates the discounted total price.
- Can you optimize derived state for performance using useMemo
?