0

I am working on my React skills and I would appreciate if you recommend me a better way of writing React code.

Here is a simple task I am currently working on: https://codepen.io/cjanes/pen/qBVaPZx?editors=0011

As you can see, in order to calculate the total price of the checked products, I need to get the array checkedItems. I choose to keep track of it inside a useEffect in TotalPrice component.

The problem is this: The TotalPrice component gets re-rendered twice, first with the last value, and then with the new calculated value.

How can I refactor my code so that it is more optimized?

1
  • Lots of time a useEffect can be useMemo which has one less render cycle. Commented Feb 4, 2022 at 15:00

1 Answer 1

1

My recommendation is that total should not be a state. Instead, it's just a derived value which you calculate from checkedItems. This makes it so that the total is always in sync with the items, and gets rid of the extra render from setting the total state:

const TotalPrice = ({ checkedItems }) => {
    let total = 0;
    checkedItems.forEach(item => total += item.price);

    console.log('TotalPrice component renders', 'total:', total)

    return ( 
        <>
            <p>Total Price is: {total}</p>
        </>
    );
}

If calculating the total was an expensive operation, you could memoize the calculation so you only repeat it when checkedItems changes:

const TotalPrice = ({ checkedItems }) => {
    const total = useMemo(() => {
        let sum = 0;
        checkedItems.forEach(item => sum += item.price);
        return sum;
    }, [checkedItems]);
Sign up to request clarification or add additional context in comments.

3 Comments

Exactly, if total remains a state, the will always be 2 renders of TotalPrice component, since one re-render if forced by the parent changing state and the second one, as different props are passed to TotalPrice, you invoke a callback that changes it's state, forcing rerender.
Thank you, first example does the job. As for the second example, won't the function always run anyway because it depends on checkedItems which changes on every checkbox click?
Yes, if checkedItems changes on ever render, the memoization will be useless. I just included it so you're aware of it for more complicated cases.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.