Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update react context outside of a consumer?

I am trying to understand how the new react context API works.

In redux, it is possible for a component to have knowledge of dispatch actions without knowing state. This allows updates to redux state without causing a rerender of components that don't care about that state.

For example I could have

<Updater onClick={updateCount}/>

and

<Consumer value={count}/>

Updater is connected to dispatch(updateCount()) and Consumer is connected to count's current value via state.count. When state.count is updated, only the Consumer rerenders. To me, that's a crucial behavior.

In react context, it seems very difficult to duplicate this behavior. I'd like to be able to update state without causing unnecessary rerenders of components that want to alter the context but don't actually care about the state.

How would it be possible for components to trigger updates to context if they are not inside a consumer? And I definitely don't want to trigger an update to the entire tree by setting state at the provider level.

like image 671
Jeremy Gottfried Avatar asked Mar 06 '19 04:03

Jeremy Gottfried


1 Answers

interesting question. Not sure you can without at least an extra layer (but happy to be shown wrong).

Maybe using Memo or PureComponent to minimise the re-rendering?

import React, { memo } from 'react';

function Widget({ setContext }) {
  return <button onClick={setContext}/>Click Me</button>;
}

export default memo(Widget);

...

function Wrap() {
  const { setSession } = useContext(SessionContext);
  return <Widget setSession={setSession} />;
}
like image 127
lecstor Avatar answered Sep 26 '22 17:09

lecstor