javascriptreact-hooksgraphqlapollo-client

In the custom React hook does useEffect fires before the return statement?


I have created a custom react hook to fetch the data using useQuery. When the user scolls the table , then next set of data is loaded. When the custom react hook is called with the next set of props, then it returns the result of the previously calculated call.

function useCustomHook(props) {

const {data, loading, error, refetch} = useQuery(query, variables: {props});
const [result, setResult] = useState({data, loading, error, refetch});

useEffect(() => {
setResult({data, loading, error, refetch});
}, [loading, error, data, refetch]);

return {result, setResult};
}

I was expecting it to return the result of the newly made call.


Solution

  • UPDATE: following the update to your code: yes, at first run, the return statement will have a null result and setResult is already immediately a function. as soon a the query is resolved, it will then update the result value to whatever code is consuming it.

    Anyway, this is still a big code smell and i think you should give a little more thought about the big picture on what you're trying to achieve

    ////////////////////////////////////////////

    I know this isn't what you asked for, but this will never work.

    const [data, setData] = useState([]);
    // and
    useEffect(() => {
      setData(data);
    }, [loading, error, data, refetch]);
    

    either way, to answer your question, if you were using useEffect and useState like we did in the past, the return statement would always resolve first with null values, and when whatever promise you would have inside useEffect is resolved, the updated values.

    I hope this helps