Link Search Menu Expand Document

Use-effect

Summary

  • https://reactjs.org/docs/hooks-effect.html
  • useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.
  • Does useEffect run after every render?
    • Yes! By default, it runs both after the first render and after every update. (We will later talk about how to customize this.) Instead of thinking in terms of “mounting” and “updating”, you might find it easier to think that effects happen “after render”. React guarantees the DOM has been updated by the time it runs the effects.
import React, { useState, useEffect } from 'react';
function Example() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:  
  useEffect(() => {    
    // Update the document title using the browser API    
    document.title = `You clicked ${count} times`;  
  });
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

advanced

useEffect(() => {
  document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes

Details

  • runs after window is painted

cook

only run on mount and unmount

If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument.

  • tells React effect doesn't depend on props or state
    • props and state inside effect will have initial values

Specify unmount

  • return a function from use effect
useEffect(() => {    
  function handleStatusChange(status) {      
    setIsOnline(status.isOnline);    
}    
ChatAPI.subscribeToFriendStatus(
  props.friend.id, 
  handleStatusChange
);    // Specify how to clean up after this effect:    
  return function cleanup() {ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);    };  
});

comparing objects

  • depend on specific properties from objects
import React, { useState, useEffect } from 'react'
import { getPlayers } from '../api'
import Players from '../components/Players'

const Team = ({ team }) => {
  const [players, setPlayers] = useState([])

  useEffect(() => {
    if (team.active) {
      getPlayers(team.id).then(setPlayers)
    }
  }, [team.id, team.active])
  return <Players team={team} players={players} />
}