Ryan
Ryan

Reputation: 79

Store state within the React Router component?

Ok, I'm pretty new to React in some ways and I am working on a simple react app that's 3 pages. I'm using react-router, partially so I can learn to use it.

On one page, I have a form that sets some state. The state obviously does not persist when you go to another route, because react-router renders a different component.

Solution #1

A solution is to have the main "App" component render one of the 3 pages/components (looking up the current route with params) and just store state there.

Solution #2

Another solution that seems obvious is storing the state in the Router component along with all the methods to update the state.

Then, I could just pass down the methods to update state to the components in the router. Seemed like a good idea, but I cannot seem to find anything online about anyone doing anything like that.

I see a lot of redux, but that's overkill for what I am doing.

So, is that possible? If it is, is there some reason that I cannot find anything about it? (Am I missing some terrible security thing or other gotchas that doing this would create.)

Upvotes: 0

Views: 1544

Answers (2)

Arpit Agrawal
Arpit Agrawal

Reputation: 1180

Instead of redux, i think you can also try react context. Ref

You can create a context in you App component and wrap your 3 page components in Context Provider to access the context. You can pass a map while creating a context, with values and setter,getter methods and use that map to change the values in your context map. You can watch this talk for better understanding.

Hope this helps.

Upvotes: 1

Anil Kumar
Anil Kumar

Reputation: 2309

Redux is what you need. Check this below approach as well.

App component

class App extends Component {
  state= {
     test: 'test'
  };

  render() {
        return (
        <Route path="/" component={() => {<Home {...this.state.test}/>}/>
      </div>
    );
  }
}

Upvotes: 0

Related Questions