Sometimes when developing react applications, we find ourselves computing a value based on a state. or a prop .
Now there are two ways to go about this. We either create a derived state, which is a state which gets updated based on the value of another state(primary state). Now with this approach , we find ourselves directly managing dependencies in a useEffect and updating the derived state when ever any of the dependency changes, this is quite hard to maintain and debug as it may not be immediately obvious how and when the derived state updates. Another issue with this approach is that , any update in the derived state will lead to uneccessary re-renders which can be avoided when the value is directly computed during render and not stored directly in a useState . These issues above can be fixed by computing the value directly during render or with a useMemo (if only the computation is expensize).
Enough already let's see some code