Update react context outside of a consumer?
Asked Answered
C

3

6

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.

Chucklehead answered 6/3, 2019 at 4:19 Comment(0)
J
1

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} />;
}
Jaejaeger answered 6/3, 2019 at 5:15 Comment(1)
github.com/reduxjs/react-redux/issues/1177 This post has some great info that might help solve the question. It seems that the newest version of redux actually has some similar setbacks with rendering, because it is also making use of the context api. I think you are right that another layer is needed, to conditionally consume context based on whether mapStateToProps is present in the connector.Chucklehead
L
0

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.

Luetic answered 6/3, 2019 at 4:38 Comment(0)
K
0

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

Koblas answered 8/1, 2021 at 13:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.