Search code examples
reactjsreduxreact-routerreact-router-v4mobx

How to use default react state as state provider instead of redux or mobx?


I am experiencing some serious fatigue when I tried wiring up redux with react router vs mobx with react router. I also tried to wire up a top level state with router's render func, but since router do not refresh, that method will fail. My state management requirement is rather simple and I am feeling redux or mobx are overkill. All I really need is a top-level state provider that acts as if just like any other component level state and use callback a way to manipulate it.

Been googling and looking at different solutions for the whole morning, however, I can't find a readily available solution with default react state that can work with react router (v4).

Is there a solution avaible? or its really something not possible to do when it comes to state with react router?


Solution

  • How did you setup Mobx? Maybe you're overthinking it. You can setup a top-level observable object that pretty much mimics the standard component state, but with all benefits of reactive programming.

    If you use the <Provider> wrapper component from the mobx-react package that store becomes accessible to all your child components using @inject. In combination with @observer any component that depends on your store will update when you change it.

    Check out this code sandbox example I created to showcase this for you: https://codesandbox.io/s/jzv73o97r5