Is there any downside to creating a state object in a parent React component and passing data up and down between nested components using useContext? Would that eliminated the need for props all together? Seems like a much easier and logical way to organize the data. Is there any performance or other concerns to this method?
Asked
Active
Viewed 3,900 times
1 Answers
8
There are a few notes that should be considered beforehand:
You can't pass data up as Data Flows Down.
Passing props between nested components will lead to an anti-pattern - "props drilling"
The solution to "props drilling" is
Context
API
But, in use of "Context Only" (as you suggest) may lead to an anti-pattern as well ("Context Hell"?),
as for every data pass, you will create a Context
and render a Provider
.
Also, the main problem I see with this approach is that every component that using context will render on change of the provider value, although they might not use the context's value.
Note the render of components 3,4
:
const Context = React.createContext();
const Child = ({ id }) => {
console.log(`rendered`, id);
return <div>Child with id = {id}</div>;
};
const UsingContext = ({ id }) => {
useContext(Context);
console.log(`rendered using Context`, id);
return <div>Using Context id = {id}</div>;
};
const MemoizedUsingContext = React.memo(UsingContext);
const Memoized = React.memo(Child);
const App = () => {
const [value, render] = useReducer(p => p + 1, 0);
return (
<Context.Provider value={value}>
<Child id={1} />
<Memoized id={2} />
<UsingContext id={3} />
<MemoizedUsingContext id={4} />
<button onClick={render}>Render</button>
</Context.Provider>
);
};

Dennis Vash
- 50,196
- 9
- 100
- 118
-
1Thank you for the example. Played around with it and cleared things up for me. – A. J. Green Mar 06 '20 at 18:46
-
The example fails with "Uncaught TypeError: dispatch is not a function" when I click the render button. – Tomás Sep 17 '21 at 12:14
-
1@TomasPrado fixed, the updated API should be reversed – Dennis Vash Sep 18 '21 at 09:32