React

React Hooks Deep Dive: useEffect, useMemo & useCallback

P

Prasanna Joshi

Author

November 12, 2024
10 min read

The Philosophy of Hooks

Hooks allow you to reuse stateful logic without changing your component hierarchy. But they come with rules.

The Dependency Array

The most common source of bugs is lying to React about dependencies. If you use a variable inside useEffect, it MUST be in the dependency array.

useMemo vs useCallback

Both are performance optimizations, but they solve different problems.

  • useMemo: Memoizes a calculated value. Use it for expensive calculations.
  • useCallback: Memoizes a function definition. Use it when passing functions to optimized child components to prevent unnecessary re-renders.
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

const memoizedCallback = useCallback(
  () => {
    doSomething(a, b);
  },
  [a, b],
);

Tags

#React#Frontend#JavaScript#Hooks

Share this article

About the Author

P

Prasanna Joshi

Content Writer

Passionate about technology and sharing knowledge with the community.

Stay Updated

Get the latest articles delivered to your inbox