Stop using useState for this 👇 You're overcomplicating your React code. The pattern: storing data in state that you could just... calculate? Example: You have a list of items. You need the total count. So you create separate state for it: - Two state variables. - Extra useEffect to keep them in sync. - More places for bugs to hide. Here's the thing: If you can calculate it during render, just calculate it. No state. No useEffect. No sync issues. Just derive it: - One source of truth. - Automatically stays in sync. - Less code to maintain. If it's expensive? Memoize it with useMemo — don't sync it with state. The rule? If it can be computed from existing data, don't store it. State is for things that CHANGE independently. Not for things you can derive. I used to over-state everything. Now I ask: "Can I just calculate this?" Most of the time? Yes. What's a piece of state you realized you didn't actually need? #React #JavaScript #Frontend #CleanCode
Adding useMemo will further optimise the recalculation on every render.
Okay - You have 1_000 same components (which do calculation like this) - You have 10_000 items What will be with your browser/event loop? In any case 1 - Fully invalid pattern 2 - Situationally
Great insight. It follows the same principle as database schema design: don’t create a separate column for something that can be derived from existing data. For example, storing a user’s age is unnecessary if we already have their date of birth.....we can always calculate the age from it.
I agree with this take. Simply because we now only have one source of truth. Which translates to easier development in the long run
Well valuable lesson. I still state a lot of things though
I have never used it like that because I remembered for some reason from the documentation that this is isn't necessary if want to calculate something from a state and it seems wasteful. However, I have done two syncing states that were bad and learned my lesson.