How handle derived state in functional components?

Viewed 2086

I'm often used class component in which we have getderivedstatefromprops method but how handle those derived state in functioncal component so anybody guide me How can I handle upcoming derived state?

2 Answers

This has a number of ways that it can be done, but the best way is situational.

Option 1: Just use a const

This works best when the value will not be impacted by events, is not a heavy calculation and does not need to be passed as a comparable reference to further down components / hooks.

const Example = ({price, quantity}) => {
    const totalPrice = price * quantity;

    return (
        <div>
            {totalPrice}
        </div>
    );
}

This method will result in the value being recalculated each time the component rerenders, but does not include an overhead for comparing dependencies and storing values that comes with useMemo.

If a non-primitive type is being calculated, such as an object, then each time the object is recalculated it will receive a new reference resulting in React's shallow comparisons failing. Depending on what you are doing with the derived value may mean this either is or is not a problem.

Option 2: Use useMemo

This works best when the value will not be impacted by events and is a heavy calculation or needs to be passed as a comparable reference to further down components / hooks.

const Example = ({price, quantity}) => {
    const totalPrice = useMemo(() => {
        return price * quantity;
    }, [price, quantity]

    return (
        <div>
            {totalPrice}
        </div>
    );
}

The method will result in the value being recalculated whenever the values in the dependency array ([price, quantity] in the example) change (reference comparison), this does include a computational overhead to compare the dependency array and determine if recomputation is required as well as a memory overhead from storing the values between rerenders.

Performance testing can be done to check whether just using a const or using useMemo would be more efficient for each scenario.

Option 3: Use useState and useEffect

This works best for values that will be impacted by events, it is also useful when values need to be passed as a comparable reference or have heavy calculations.

const Example = ({price, quantity}) => {
    const [totalPrice, setTotalPrice] = useState(price * quantity);
    
    useEffect(() => {
        setTotalPrice(price * quantity);
    }, [price, quantity]

    return (
        <div>
            {totalPrice}
            <div onClick={() => setTotalPrice(current => current * 2)}>
                Double Total Price
            </div>
        </div>
    );
}

This method will result in a new value being stored whenever the setState function is called (setTotalPrice in the example). To achieve the update based on the props changing a useEffect can be used with a dependency array ([price, quantity] in the example) that will run whenever the related properties change (reference comparison).

The method also allows for the value to be impacted by other events that are able to call the setState function (see the onClick in the example).

Conclusion

This is not a comprehensive list but it covers the basic options.

There are options for more complex state management using code external to React or using React's Context.

use the useEffect hook, you can read more here

Related