Understanding useCallback vs useEffect: A Dive into React Hooks with IntersectionObserver

Christopher Beards
3 min readAug 28, 2023

As you venture deeper into the React ecosystem, you encounter various hooks designed to manage state, side effects, and performance. Two such hooks are useEffect and useCallback. Though they may appear similar at first glance, they serve distinct purposes. In this article, we’ll explore the differences between these two hooks and when to use each, using the IntersectionObserver as our guide.

The Basics

1. useEffect: This hook lets you perform side effects (like data fetching, manual DOM manipulations, and setting up subscriptions) in function components. It’s the equivalent of componentDidMount, componentDidUpdate, and componentWillUnmount in class components.

2. useCallback: Returns a memoized callback. It’s perfect for preserving the identity of a function and preventing unnecessary renders or computations.

The Scenario: Implementing IntersectionObserver with React

Suppose we’re building a “Load More” feature that detects when a user has scrolled to the bottom of a list and then fetches more items.

Using useEffect:

You might initially think of using useEffect to set up and tear down the IntersectionObserver:

function LoadMoreComponent() {
useEffect(() => {
const observer = new IntersectionObserver((entries) => {
// handle intersections
});

--

--

Christopher Beards

A meditation teacher & software engineer passionate about personal development, poetry, consciousness, & problem-solving.