4

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?

A. J. Green
  • 93
  • 2
  • 8

1 Answers1

8

There are a few notes that should be considered beforehand:

  1. You can't pass data up as Data Flows Down.

  2. Passing props between nested components will lead to an anti-pattern - "props drilling"

  3. 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>
  );
};

Edit blue-meadow-0pxzr

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118