React Context Provider Gotcha

splodingsocks profile image Murphy Randle ・1 min read

I used a global state store in my React Native app for data that needs to be available to multiple screens. I used a library to do this:
https://github.com/jamiebuilds/unstated-next, but it’s basically just a combo of React’s useState and useContext.

The problem was, screen B added data to the global store of things, then navigated back to screen A. But screen A would never have the updated state. It was almost like there were two separate stores, one for each page 🧐.

I was just beginning to pursue this thought when I remembered that React’s context “Provider” does make a new copy of the state for any children below itself in the tree. I was wrapping each of the pages in its own provider! Once I wrapped the whole app in a single Provider component, both pages were sharing the same state again, and page B’s triggered updates immediately reflected on page A.

react #state #context


markdown guide