Looking at the React documentation for Context, the context is used without the .Provider property:
import { LevelContext } from './LevelContext.js';
/*
LevelContext is defined as
export const LevelContext = createContext(0);
*/
export default function Section({ children, isFancy }) {
const level = useContext(LevelContext);
return (
<section className={
'section ' +
(isFancy ? 'fancy' : '')
}>
<LevelContext value={level + 1}>
{children}
</LevelContext>
</section>
);
}
As you can see, LevelContext
is used, rather than LevelContext.Provider
.
However, in the documentation to use contexts with reducers, and in any other places on internet, the context is used with the .Provider property:
import { useReducer } from 'react';
import { TasksContext, TasksDispatchContext } from './TasksContext.js';
/*
The contexts are defined as
export const TasksContext = createContext(null);
export const TasksDispatchContext = createContext(null);
*/
export default function TaskApp() {
const [tasks, dispatch] = useReducer(
tasksReducer,
initialTasks
);
// omitting non relevant code...
return (
<TasksContext.Provider value={tasks}>
<TasksDispatchContext.Provider value={dispatch}>
<h1>Day off in Kyoto</h1>
</TasksDispatchContext.Provider>
</TasksContext.Provider>
);
}
// omitting non relevant code
I tried both versions, and both work. So I am confused, when should I use .Provider and when not?
Both ways are good, Usign the context directly without "Provider" property is a feature of React 19 version
For more information you can have a look on react 19 post with the new features released on the framework
https://react.dev/blog/2024/12/05/react-19#context-as-a-provider