Member-only story

As discussed in the part 1 — there are multiple scenarios where useEffect is overhead.

Say if you want to process the props and render it in the UI, below is the obvious choice of coding, we would get the expected output but it is not the clean (or right) way to do

Both state and effect is unnecessary

When props items or filter is changed

  • UI will be re-rendered with the latest values.
  • useEffect handler function will be invoked as items and filter are its dependency
  • filteredItems state will be updated
  • UI will be re-rendered with the latest values once again.

Instead of these redundancies, we can replace both the state and effect with a plain javascript variable

If processItems functions takes less time, this is okay,

Now, when props items or filter is changed

  • UI will be re-rendered with the latest values.

We skipped three steps, and simplied the code, with the same result

If processItems functions takes lot of computation time, we don’t want to do it every re-renders, so we can cache (or ‘memoize’) by wrapping it in a useMemo hook, so that it will be executed only when it is needed

now processItems will be called only when items or filter changed

Please refer to the eligibility rules for making it as a state (https://medium.com/@vinodht/eligibility-rules-for-making-it-as-a-state-react-eca0b579c0f0)

--

--

Vinodh Thangavel
Vinodh Thangavel

Written by Vinodh Thangavel

Passionate lifelong learner, coding enthusiast, and dedicated mentor. My journey in tech is driven by curiosity, creativity, and a love for sharing knowledge.

No responses yet