componentWillUnmount
), you return
a function from your effect function.count
, you’d tell the effect to look for any changes in the state of count
, and disregard re-renders because of other changes1useEffect(() => {
2 document.title = `You clicked ${count} times`;
3}, [count]); // Only re-run the effect if count changes
Example effect
1useEffect(() => {
2 function handleStatusChange(status) {
3 setIsOnline(status.isOnline);
4 }
5
6 ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
7
8 // return a function to sepcify how to cleanup after the effect
9 // you can return a named function for brevity: return function cleanup() {
10 return () => {
11 ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
12 };
13}, [props.friend.id]); // Only re-subscribe if props.friend.id changes