Skip to main content

Deriving State

This example demonstrates the best practice of deriving information directly from existing state or props in React, rather than creating additional state variables for derived values.
For example, the totalPrice can be directly calculated by multiplying the quantity by PRICE_PER_ITEM, rather than creating a separate state variable for it.

This approach prevents unnecessary state management and keeps the code simpler and more efficient.

Similarly, calculating derived values inside useEffect is also a mistake, as it introduces unnecessary complexity and potential performance issues.
If you have data that can be computed from existing state, like a full name from firstName and lastName, it's better to compute it directly within the render rather than using separate state hooks.

import { useEffect, useState } from "react";

const PRICE_PER_ITEM = 10;

const Five = () => {
// Information can be derived from state / props - it is better to derive information from state
const [quantity, setQuantity] = useState(1); // after updating this state, the entire component will re-render
const totalPrice = quantity * PRICE_PER_ITEM;
// creating a separate state for such a calculated field is a mistake
// const [totalPrice, setTotalPrice] = useState(0);

const handleClick = () => {
setQuantity((el) => el + 1);
};

// calculating the field inside useEffect is a mistake
// useEffect(() => {
// setTotalPrice(quantity * PRICE_PER_ITEM);
// }, [quantity]);

return (
<div>
<button
onClick={handleClick}
className="bg-blue-500 px-4 py-2 text-white rounded mb-5"
>
Add item
</button>

<p>Total price: {totalPrice}</p>
</div>
);
};

export default Five;

// Another good example is if you have first name and last name,
// there's no need to create a separate hook to derive the full name