What is useState in React?
As stated in the official documentation,
useState is a React Hook that lets you add a state variable to your component.
To fully understand the differences from useMemo, however, it’s helpful to first consider React's design philosophy ⛩️
React's design philosophy: Declarative UI
React’s declarative UI principle ensures re-renders and reconstructs the UI on each user interaction to ensure idempotency, which makes building applications simpler and more predictable than with imperative UI principles.
While React’s Virtual DOM optimises updates by changing only the parts that differ, useState is central to managing these changes.
Tradeoff
However, frequent re-renders can be costly when the codebase involves intensive computations or heavy rendering.
To address this, useMemo becomes essential. According to the official documentation,
What is useMemo in React?
useMemo is a React Hook that lets you cache the result of a calculation between re-renders.
This feature is valuable when dealing with computationally expensive tasks, as useMemo can bypass re-computation by retrieving data from the cache.
useMemo or useState
That said, there’s ongoing debate on the optimal use of useMemo, as it involves evaluating dependencies and using memory, which can add overhead. The official guidance notes,
In general, unless you’re creating or looping over thousands of objects, it’s probably not expensive."
More on this topic is available here: https://react.dev/reference/react/useMemo#how-to-tell-if-a-calculation-is-expensive
They are kind enough to share how to measure the time spent on the function execution.
console.time('filter array');
const visibleTodos = filterTodos(todos, tab);
console.timeEnd('filter array');
Pitfall (Digressing Slightly)
Lastly, an important consideration: useMemo compares dependencies with Object.is()
, meaning changes within the same object reference will not trigger re-evaluation.
This is a key pitfall to keep in mind.
Take Aways
React employs the design philosophy Declarative UI which takes it granted that some functions are called more than necessary at the expense of simple code experience.
In order to reduce the overhead useMemo is here for you.
Thank you!
Top comments (0)