I'm using React to pass a function from a parent component to a child component and trying to run it in the useEffect() hook.
Parent
function Parent(props) {
function alertMe() {
alert('me');
}
render (
<div>
<Child alertMe={alertMe} />
</div>
);
}
Child
function Child(props) {
const { alertMe } = props;
useEffect(() => {
alertMe();
}, [alertMe]);
render (
<div>
// stuff
</div>
);
}
If I remove alertMe as a dependency in the useEffect() of the Child component, it only fires once, but I get a warning:
React Hook useEffect has missing dependencies: 'alertMe'. Either include it or remove the dependency array react-hooks/exhaustive-deps
The alertMe function is defined once in the Parent component on load, so I don't understand why it would run endlessly in the Child component. It's not changing like state.
How can I add alertMe as a useEffect() dependency but still only run it once?
useEffect. If you give useEffect an empty array as the second argument it will only run on mount. - skellertor