reactjsreact-contextcreatecontext

How to use createContext with a hook


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={{
        scheduleStartDate: scheduleStartDate,
      }}
    >
      {children}
    </ScheduleContext.Provider>

Error I get: Invalid hook call. Hooks can only be called inside of the body of a function component.


Solution

  • 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:

    export const ScheduleContext = createContext(null);
    // ...
    const MyProvider = ({ children }) => {
      const utils = useUtils();
      return (
        <ScheduleContext.Provider value={{ 
          scheduledStartDate: utils.date().add(2, "days")
        }}>
          {children}
        </ScheduledContext.Provider>
      )
    }