FrontendDeveloper.in

React question detail

What would the context value be for no matching provider?

When a component calls useContext(SomeContext) but no matching <SomeContext.Provider> is present higher up in the component tree, the default value passed to React.createContext(defaultValue) is returned.

const ThemeContext = React.createContext('light'); // 'light' is the default value

function ThemedComponent() {
const theme = useContext(ThemeContext);
return <div>Current theme: {theme}</div>;
}

// No ThemeContext.Provider anywhere in the tree

In this case, theme will be 'light'. It's the default value you provided when you created the context.

Note: If you don’t specify a default value, the context value will be undefined when used without a provider:

const AuthContext = React.createContext(); // No default

function Profile() {
const auth = useContext(AuthContext);
// auth will be undefined if there's no AuthContext.Provider
}
Back to all React questions
Get LinkedIn Premium at Rs 399