I have a useEffect that I want to avoid the first run. So I did a hook to check if it's the first render:
useFirstRender
import { useRef, useEffect } from 'react';
export function useFirstRender() {
const firstRender = useRef(true);
useEffect(() => {
firstRender.current = false;
}, []);
return firstRender.current;
}
And I want to use it like that
const firstRender = useFirstRender();
const [isOpen, setOpen] = useState<boolean>(false);
useEffect(() => {
if (firstRender) {
return;
}
/* Rest of logic using `isOpen` dependency */
}, [isOpen, firstRender]);
Choice 1: With firstRender as useEffect's dependency
This dependency will re-render the useEffect when firstRender become false, so will make it useless.
Choice 2: Without firstRender as useEffect's dependency
This will make the logic working fine, but building it will cause a warning:
Warning: React Hook useEffect has a missing dependency: 'firstRender'. Either include it or remove the dependency array. react-hooks/exhaustive-deps.
What's the best solution ?!
- Do I have a solution using only logic and development ?
- I know that I can add a comment
// eslint-disable-lineto disable that.. But is it normal to do so ? I find it strange to have to do this when it is the expected behavior. Or can I define the fields I want to disable (and keep the original behavior)
Do I miss something ?! Why do a Eslint rule stop you to do something useful ? I know that I don't want that dependency !?