DEV Community

Discussion on: useEffect missing dependency, need advice

Collapse
 
sabbin profile image
Sabin Pandelovitch • Edited

Try wrapping your hydrate function into a useCallback hook, also use the callback in the setState function not the state it self so you don't have to set a dependency to it, the same goes for the Errors state object

const hydrate = useCallback(( _state, _errors=false ) => {
    console.log('hydrate()');
    setState(prevState => ({...prevState,..._state}));
    if(_errors){
        setErrors(prevErros => ({...prevErrors,..._errors}));
    }
},[]);
Enter fullscreen mode Exit fullscreen mode

After that add the hydrate to your useEffect() dependency array,

useEffect(()=>{
    hydrate({
        name:'Garrett',
        email:'test@test.com',
        newsletter: 'yes'
    });
},[hydrate]);
Enter fullscreen mode Exit fullscreen mode

As the hydrate function has no dependencies it will be initialised only once. So your effect should be executed only once.

Please try and see if this helps you

Collapse
 
r3wt profile image
Garrett R. Morris

Ironically this is exactly what i ended up doing. Thanks for sharing though, as someone who is new to hooks, its very helpful to learn about useCallback(). i think now i will refactor much of my code to take advantage of this feature.

Collapse
 
sabbin profile image
Sabin Pandelovitch

useCallback and useMemo are very useful to know. I think I'll post something on this subject as it's good to know when and where to use them