Created
April 20, 2022 11:42
-
-
Save joenas/7a03f64d84290efd59917140fd899fb7 to your computer and use it in GitHub Desktop.
React useOnce hook for one-time effects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useRef } from 'react'; | |
const useOnce = (effect) => { | |
const didUse = useRef(false); | |
useEffect(() => { | |
if (didUse.current === false) { | |
didUse.current = true; | |
effect(); | |
} | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
}, []); | |
}; | |
export default useOnce; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment