So in React, the rules of hooks says that hooks cannot be called outside of functional components.
My predicament: I need to initialize state in my createContext using a hook for the SchedulesProvider. The state is a dynamic date, like two days from the current date. Hooks can’t be called outside of functional components. createContext cannot be called within the provider component because it needs to be exported and live outside of the SchedulesProvider.
What I’ve tried
const utils = useUtils(); //useUtils is a hook from a date library
export const ScheduleContext = createContext({
scheduleStartDate: utils.date().add(2, "days"), //using the hook here
...
});
My provider is trying to pass the state down like so…
const { scheduleStartDate } = useContext(ScheduleContext);
<ScheduleContext.Provider
value={{
scheduleEndDate: scheduleEndDate,
}}
>
{children}
</ScheduleContext.Provider>
Error I get: Invalid hook call. Hooks can only be called inside of the body of a function component.
2
Answers
You probably don’t need a default value for your context. The default value is only used if there is no
ScheduledContext.Provider
higher up the component tree, and you can arrange your components so that never happens.If you don’t need a default value, you can wait until you are rendering the provider to call
useUtils
. For example:The value you pass to
createContext()
is more like a fallback for when it’s used outside of your context provider hierarchy.From createContext()
Set the real value with your own provider component instead
I prefer to set a real-ish value for two reasons…