1.1 KiB
1.1 KiB
title, type, tags, author, cover, dateModified
| title | type | tags | author | cover | dateModified | ||
|---|---|---|---|---|---|---|---|
| React useEffectOnce hook | snippet |
|
chalarangelo | pop-of-green | 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 thewhencondition changes. - Check if
whenistrueand the effect has not executed before. If both aretrue, runcallbackand sethasRunOncetotrue.
const useEffectOnce = (callback, when) => {
const hasRunOnce = React.useRef(false);
React.useEffect(() => {
if (when && !hasRunOnce.current) {
callback();
hasRunOnce.current = true;
}
}, [when]);
};
const App = () => {
const [clicked, setClicked] = React.useState(false);
useEffectOnce(() => {
console.log('mounted');
}, clicked);
return <button onClick={() => setClicked(true)}>Click me</button>;
};
ReactDOM.createRoot(document.getElementById('root')).render(
<App />
);