Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
React useEffect cheat sheet

Run once

similar to componentDidMount

import { useEffect } from 'react'

export default function Component() {
    useEffect(() => {
        // code to run when component mounts
    }, []) // pass empty array

    return <> ... </>
}

Run on props change

similar to componentDidUpdate

import { useEffect } from 'react'

export default function Component({ prop }) {
    useEffect(() => {
        // code to run when given props change
    }, [prop]) // props to watch

    return <> ... </>
}

Run after every render

similar to componentDidUpdate

import { useEffect } from 'react'

export default function Component() {
    useEffect(() => {
        // code to run after every update
    }) // (no second argument)

    return <> ... </>
}

Run on state change

similar to componentDidUpdate

import { useState, useEffect } from 'react'

export default function Component() {
    const [state, setState] = useState()

    useEffect(() => {
        // code to run when given states change
    }, [state]) // states to watch

    return <> ... </>
}

Run on unmount

similar to componentWillUnmount

import { useEffect } from 'react'

export default function Component() {
    useEffect(() => {
        return () => {
            // code to run when component unmounts
        }
    })

    return <> ... </>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment