Member-only story
No — UseEffect is not required — part -2
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
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
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
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)