Skip to content

Instantly share code, notes, and snippets.

@yairEO
Created May 23, 2020 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yairEO/e617c9b4329c8a9d46e401ffcf12ffc9 to your computer and use it in GitHub Desktop.
Save yairEO/e617c9b4329c8a9d46e401ffcf12ffc9 to your computer and use it in GitHub Desktop.
React useEffect - disable execution on first load
import React, { useEffect, useRef } from 'react';
const useDidMountEffect = (func, deps) => {
const didMount = useRef(false);
useEffect(() => {
if (didMount.current) func();
else didMount.current = true;
}, deps);
}
export default useDidMountEffect;
@yairEO
Copy link
Author

yairEO commented May 23, 2020

Usage example:

import React, { useState, useEffect } from 'react';

import useDidMountEffect from '../path/to/useDidMountEffect';

const MyComponent = (props) => {    
    const [state, setState] = useState({
        key: false
    });    

    useEffect(() => {
        // you know what is this, don't you?
    }, []);

    useDidMountEffect(() => {
        // react please run me if 'key' changes, but not on initial render
    }, [state.key]);    

    return ...
}

@yairEO
Copy link
Author

yairEO commented May 23, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment