Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace props with useContext in React Application

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?

like image 468
A. J. Green Avatar asked Nov 02 '25 06:11

A. J. Green


1 Answers

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

like image 104
Dennis Vash Avatar answered Nov 03 '25 23:11

Dennis Vash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!