When I call getRequestContext anywhere in my app after I have updated context, my callback does not use the new value, but instead always uses the old value. Any ideas on how to ensure that I always retrieve the most up to date context value when getRequestContext is called?
export function useData() {
const context = useContext(dataStateContext);
if (context === undefined) {
throw new Error("useData must be used within a dataProvider");
}
const getRequestContext = useCallback(async () => {
const requestContext = {
headers: context.headers,
env: context.env,
id: context.id ?? ""
};
return requestContext;
}, [context]);
return {
getRequestContext,
};
}
2
Answers
I solved it by using a ref, below is the updated code.
you can use
useEffect()
hook to trigger the re-renders when the context change happens,