DEV Community

Pere Sola
Pere Sola

Posted on

React Context API - why do we pass a defaut value to React.createContext()?

I was refreshing on React's Context Api today. It works like:

  • You create a Context: export const TestContext = React.createContext(defaultValue)
  • You add a provider: <TestContext.Provider value={whenever: "whatever"} />
  • You grab the value passed via Context in whatever nested Component: const value = React.useContext(TestContext). value will be {whenever: "whatever"}.

So, we grab the value passed in the TestContext.Provider value prop. What about the defaultValue we passed in React.createContext(defaultValue)? Well, it turns out that is pretty much useless unless the nested component does not have a TestContext.Provider above it. It is explained here.

Try it out: pass {whenever: "whoever"} as default value in createContext, like React.createContext({whenever: "whoever"}), and remove the <TestContext.Provider />. The value from useContext will be {whenever: "whoever"}.

Another cool thing that I realised in the React & Typescript course in Frontend Masters is that I can create a wrapper for the <TestContext.Provider value={whatever} />. It goes like:

export const ThemeProvider = ({children}) => {
     return <TestContext.Provider value={{whenever: "whatever"}}>{children}</TestContext.Provider>
Enter fullscreen mode Exit fullscreen mode

In your App.js, you just need to import and add <ThemeProvider></ThemeProvider>.

Top comments (0)