0

I have a React app that takes the user through various steps. I want to have the ability to use the browser's "back" button to go back to a previous step. Now I'm thinking of using react-router to do this.

Currently, I am simply reacting to events and calling setState on my top-level component.

My question: Does all state have to be reflected in the URL, or saved into local storage? Or can I keep the component's state and just have react-router change some props on the top-level component? When I do that, do I risk loosing the component's state (e.g. because React doesn't identify the old and the new components)?

I want to have simple URLs like /step1, /step2... . These do not reflect everything that is going on in the app. Specifically, I don't need or want the ability to directly enter such an URL. There are also privacy concerns. I am happy with having the application's state in the main component's ephemeral state. In other words, my application's state is not a pure function of the route.

I want to mainly use react-router to make the back button act as a glorified undo / go to last step button, and only secondly to navigate to other components. Any idea or small snippet showing how to do that? Or is react-router not suited for this?

jdm
  • 9,470
  • 12
  • 58
  • 110
  • If you change components, then you'd have to pass the parameters as props if you don't want to leverage react-router's parameters, IMHO. I think that you could also have all the app state live in a parent component and have them change by passing callbacks as props to children (which will probably lead into a big mess if it is app wide). – Sumi Straessle Sep 06 '17 at 12:36
  • What you might wan't to checkout, is using props instead of state if you want to pass something into a different page, and checkout redux, super easy pattern and you can dispatch data on different views. – TGarrett Sep 06 '17 at 12:40

1 Answers1

0

When React navigates from one component hierarchy to another (such as react-router links / history navigation) it only unmounts the components that do not exist in the new component hierarchy. State is only lost in unmounted components. If your state is properly stored at the top level which only goes through rerendering and not remounting, you should retain it.

jlaitio
  • 1,878
  • 12
  • 13
  • Thanks, but isn't necessarily at the top level with react-router? So my component would have to be at a lower level... I've also found that you can keep everything on one route and use `props.params`, but I'm not sure this is a good idea (https://stackoverflow.com/a/36264389/143091). – jdm Sep 06 '17 at 12:52
  • Let me rephrase: your state doesn't need to be at the *absolute top level*. Just on a level that doesn't go through unmounting as the properties propagated to your app by react-router (from the url path) change. – jlaitio Sep 06 '17 at 12:59