Search code examples
reactjsreact-hooksnext.jsuse-statereact-query

state set inside react-query useQuery hook reseting to initial state on windows focus


I have this code, that on the first build works fine

const [conditionState, setConditionState] = useState([])

const { data: solicitud, error } = useQuery(['SOLICITUD', _id], async () => {
     const { data } = await axios.get(`/api/solicitudes/${_id}`);

    setConditionState(data.condiciones)
    return data.solicitud;
}, {
    refetchOnWindowFocus: false,
})
if (error) console.log(error);

The problem is that, when I change tabs and back to the application (re-focusing on the app window) the conditionState is set back to it initial state, iI understand that the code inside the useQuery hook is not running again due to the refetchOnWindowsFocus being false, but isn't the useState hook supposed to be the last state before updating, which supposedly should be data.condiciones?

Btw solicitud still the same after the refocus, is there something about the hooks that I'm not understanding?


Solution

  • The only way the conditionState is set back to the initial state is because the component got remounted. Something is triggering a re-rendering from the top tree of this component.