Link Search Menu Expand Document



  • 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 (
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me


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


  • runs after window is painted


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) {      
);    // Specify how to clean up after this effect:    
  return function cleanup() {ChatAPI.unsubscribeFromFriendStatus(, 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 ( {
  }, [,])
  return <Players team={team} players={players} />