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.