Categories
React Answers

How to fix the cleanup function from React useEffect being called on every render?

Spread the love

To fix the cleanup function from React useEffect being called on every render, we should add items into the array in the 2nd argument so that the callback is only called when those items are changed.

For instance, we write

useEffect(() => {
  chatAPI.subscribe(props.friend.id);

  return () => chatAPI.unsubscribe(props.friend.id);
}, [props.friend.id]);

to call useEffect to watch the props.friend.id prop value for changes.

When this changes, the callback is called.

And the we return a function in the callback cleans up when props.friend.id is changed.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *