react.dev icon indicating copy to clipboard operation
react.dev copied to clipboard

Clarification about multiple contexts on "Scaling Up with Reducer and Context" documentation page

Open samanpwbb opened this issue 3 years ago • 1 comments
trafficstars

Hi, new react docs are great. I had a question about the sample code in Scaling Up with Reducer and Context. I hope this is a reasonable way to provide feedback on a specific page. I did a quick issue search and didn't find anything related. Here is some of the sample code:

import { TasksContext, TasksDispatchContext } from './TasksContext.js';

export default function TaskApp() {
  const [tasks, dispatch] = useReducer(tasksReducer, initialTasks);
  // ...
  return (
    <TasksContext.Provider value={tasks}>
      <TasksDispatchContext.Provider value={dispatch}>
        ...
      </TasksDispatchContext.Provider>
    </TasksContext.Provider>
  );
}

It's interesting that you chose that style vs:


```js
import { TasksContext, TasksDispatchContext } from './TasksContext.js';

export default function TaskApp() {
  const [tasks, dispatch] = useReducer(tasksReducer, initialTasks);
  // ...
  return (
    <TasksContext.Provider value={{ tasks, dispatch }}>
        ...
    </TasksContext.Provider>
  );
}

If I understand correctly, the benefit of multiple contexts comes in when I've memoized a component that is a child of our contexts, and then I want to use dispatch inside that child component without subscribing to changes to tasks.

This seems either important to elaborate on in the documentation page, or if you don't want to make the page more complex, maybe it'd be simpler for everyone to just use one context? One potential problem with the sample code you've chosen to share, and without explanation, is that it suggests the use of a lot of contexts, one for every bit of data you might want to share, which can lead to overwrought code in my opinion.

samanpwbb avatar Oct 11 '22 17:10 samanpwbb

Hi there, I see the potential optimization benefits of employing a splitting context approach. However, the example provided in the documentation might lead to some misconceptions. Could you please consider extending the example with optimization benefits? Alternatively, it might be preferable to adhere to using a single context from original question from @samanpwbb

Here is a recorded video of using example from docs that demonstrates re-rendering of the entire application upon each dispatch

https://github.com/reactjs/react.dev/assets/6339002/f8218153-02b0-4b9a-af91-36763888d24d

dresha-dev avatar Feb 02 '24 15:02 dresha-dev