3

I'm working in a codebase that has a bunch of redux already working for managing and persisting state, as well as dispatching actions. My goal with the new Context API is to get rid of the prop-drilling that I have to do to deliver all these pieces of state to various components but keep the existing code for managing state in redux.

Now I've removed the excessive prop drilling code and replaced them with context Providers and Consumers, hooking them up in my components in all the right places. I'm still dispatching actions to redux and getting API responses populating my redux store, and I want to somehow notify the contexts to update when specific parts of the redux store update.

How do I get updates from the redux store delivered into my different Providers?

Nick
  • 9,792
  • 7
  • 50
  • 60

1 Answers1

4

Since you are using the new Context Api, you can easily connect the component that uses the Context Provider with redux store and update the context values like

const Context = React.createContext();
class App extends React.Component {
   state = {
       user: ''
   }
   static getDerivedStateFromProps(nextProps, prevState) {
       if(nextProps.user !== prevState.user) {
          return {user: nextProps.user}
       }
       return null;
   }
   render() {
       return <Context.Provider value={this.state.user}>
           <MyComponent />
       </Context.Provider>
   }
}
const mapStateToProps(state) {
   return {
      user: state.user
   }
}
export default connect(mapStateToProps)(App);
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400