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?
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>
  );
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With