Why is React useState dependency empty in callback?

Viewed 1783

The dependency used in the useCallback is coming as null even though it is populated when calling it outside of the useCallback. I even tried removing the useCallback and used the data variable inside a regular function. It is still null. Any idea why this is happening?

const [data, setData] = useState(null);

useEffect(() => { //on page load
  const data = fetchData();
  setData(data)
}, []);

const func = useCallback(async (payload) => {
    console.debug(data); //null
    if (data) //call api with payload
}, [data]);

console.debug(data); //correct population of data

return <MyComponent onSubmit={func} /> //passed to and called from second child down from here
2 Answers

Do it like this

  1. Pass the data as a parameter in useState to the function.Never mind i don't have data.So i used 'abc'.

    useEffect(() => { //on page load
     const data = 'abc';
     setData(data)
     func(data)
      }, []);
    
  2. Next step take the data as a parameter in function.

     const func = (data) => {
         console.log(data); //now it will have abc
     };
    

The only way I could get this to work in all cases was to move func() down to the child...where it's used. And because data is used in both parent and children, I passed it down to the children and pushed any modifications to it back up to the parent after running func() so the modified data could be set() in the parent.

Related