Use the URL as the source of truth in React

Share this video with your friends

Send Tweet

In Single Page Apps we're used to fetch the data on event callbacks. That disables the capacity to use the URL to share it to someone else and get to the same state of the app, just like in non Single Page Apps.

This lesson shows you how to use React and React Router to use the URL as the source of truth for your app state.

Kevin
~ 7 years ago

Thanks for the quick explanation. I also have a question, why did you set the window.location instead of using react-router's methods of changing location like push/replace/go?

Also, how can you handle back/forward buttons to read the state of the query params from the history?

Jan Borchers
~ 7 years ago

Yes, thank you! I was wondering the same thing though.

And conversely, if you're happy manipulating window.location directly, why not get the search value directly from there without needing react-router at all?

Alex Jover Moralesinstructor
~ 7 years ago

Is just a matter of preference, you can use react-router's methods for that. I use react-router to show a more real-world example (since most apps use it) and it pushes the location variable as a property, so you can react to it.

Stephen
~ 7 years ago

How does this work now with react-router-dom the latest react router (4)?

Alex Jover Moralesinstructor
~ 7 years ago

It is using version 4 of react router ;)