Jeremy Gottfried
Jeremy Gottfried

Reputation: 1201

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.

Upvotes: 6

Views: 3385

Answers (3)

user3550446
user3550446

Reputation: 455

you can try this library react-hooks-in-callback to isolate the context from your component and pick only desired state values from it,

check this example

Upvotes: 0

lecstor
lecstor

Reputation: 5707

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} />;
}

Upvotes: 1

strblr
strblr

Reputation: 950

One possible solution is to transform your consumer components into pure components and check against the values each component really cares about.

This can be easily done using the onlyUpdateForKeys HOC from recompose.

Upvotes: 0

Related Questions