I'm trying to figure out how to make my React SPA app maintain state when the user navigates with the back/forward browser buttons. E.g. the user is filling a form, then he moves back and forward and the form is automatically restored.
I reviewed many JavaScript routers around but none seem to address this issue properly... (or even at all).
Currently I'm using React Router 4 and this is the pattern I'm adopting:
- when programmatically leaving the page, I first save current page's state with
history.replace(this.state)
; then I move out of the page withhistory.push(newLocation)
- when a page component is created (
componentWillMount
) I check forthis.props.location.state !== undefined
and if so, I restore it withthis.setState(this.props.location.state)
My question is: is the above pattern correct? suggested? Is there any better and widely adopted way?