From 15caeb286f873d6424caead15d6aa4cf6dd74aad Mon Sep 17 00:00:00 2001 From: Chalarangelo Date: Fri, 5 Nov 2021 20:31:34 +0200 Subject: [PATCH] Add useEffectOnce --- snippets/useEffectOnce.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 snippets/useEffectOnce.md diff --git a/snippets/useEffectOnce.md b/snippets/useEffectOnce.md new file mode 100644 index 000000000..f06f78e9b --- /dev/null +++ b/snippets/useEffectOnce.md @@ -0,0 +1,35 @@ +--- +title: useEffectOnce +tags: hooks,effect,beginner +firstSeen: 2021-11-16T05:00:00-04:00 +--- + +Runs a callback at most once when a condition becomes true. + +- Use the `useRef()` hook to create a variable, `hasRunOnce`, to keep track of the execution status of the effect. +- Use the `useEffect()` that runs only when the `when` condition changes. +- Check if `when` is `true` and the effect has not executed before. If both are `true`, run `callback` and set `hasRunOnce` to `true`. + +```jsx +const useEffectOnce = (callback, when) => { + const hasRunOnce = React.useRef(false); + React.useEffect(() => { + if (when && !hasRunOnce.current) { + callback(); + hasRunOnce.current = true; + } + }, [when]); +}; +``` + +```jsx +const App = () => { + const [clicked, setClicked] = React.useState(false); + useEffectOnce(() => { + console.log('mounted'); + }, clicked); + return ; +}; + +ReactDOM.render(, document.getElementById('root')); +```