useMemo()

Understanding useMemo in Modularjs

useMemo is a hook provided by Modularjs that allows you to memoize computed values inside your modular components. It helps optimize performance by recalculating values only when their dependencies change, rather than on every re-render.

This is especially useful for expensive calculations or derived state that shouldn’t be recomputed unnecessarily.


What is useMemo ?

  • useMemo lets you cache the result of a computation between renders.

  • It returns the memoized value.

  • The computation is re-executed only when one of its dependencies changes.


How to use useMemo

Here is a simple example showing how to use useMemo to calculate a derived value inside your Modularjs component:

module.exports = ({ useState, useMemo }) => {
  const [count, setCount] = useState(0);

  const double = useMemo(() => {
    console.log('Recalculating double...');
    return count * 2;
  }, [count]);

  return (
    <div>
      <h1>useMemo Example</h1>
      <p>Count: {count}</p>
      <p>Double: {double}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};

Explanation:

  • useMemo(() => count * 2, [count]) Calculates count * 2 but only recalculates when count changes.

  • If the component re-renders without count changing, the memoized value is reused.

  • This saves unnecessary computation and improves efficiency.


Another Example: Filtering a List

Explanation:

  • useMemo(() => ..., [query]) ensures filtering only happens when query changes.

  • Typing in the input triggers recalculation, but re-renders without input changes won’t cause filtering again.

  • This improves performance for large lists.


Tips for Using useMemo

  • Use useMemo for expensive calculations or derived values that don’t need recalculating every render.

  • Avoid overusing it for trivial calculations — it adds unnecessary complexity.

  • Always include the correct dependencies in the dependency array. Missing dependencies may lead to stale values.


This page gives you the core knowledge to start optimizing your Modularjs components with useMemo! 🚀

Last updated