DEV Community

An alternative to handle state in React: the URL !

GaelS on June 01, 2018

For a french version of this article, go here :) The state of a react app Managing the global state of a React app is an endless war be...
Collapse
 
joshuaai profile image
Josh Ihejiamaizu • Edited

Thank you @GealS for this. The example for search is a great way to use query params (QPs).

  1. In terms of more advanced component patterns though, do you have any use cases where you can optimize performance/minimize loading by using query params?

  2. By using QPs, can you somehow mitigate the almost endless return to previous routes that's triggered by history when users click the back button? I'm assuming that QPs allow you update UI without actual route changes? So does this translate to history only going back to route changes and not query changes?

Collapse
 
jacobmoyle profile image
Jacob

Regarding point #2:
History.replaceState(...) may solve your problem:

The History.replaceState() method modifies the current history entry, replacing it with the stateObj, title, and URL passed in the method parameters. This method is particularly useful when you want to update the state object or URL of the current history entry in response to some user action.

Collapse
 
gaels profile image
GaelS • Edited

Hi, thanks for the feedback :)
i'll try to answer the 2 points you raised :

  1. Despite the use of the QPs, as I see it, optimizing the loading would mean optimizing the request over the network. So far, I only come up with general ideas (which come regardless QPs) such as caching, smart prefetching (= the request being sent before the user even hits enter), and things like that.

  2. As I understand your question here, to save bandwidth and improve UX, I think caching the requests' responses could be - again-the solution here. With QPs, going back in history means querying something you already have so, better use a cache (which comes for free with react-apollo for instance).

Collapse
 
joshuaai profile image
Josh Ihejiamaizu

Thanks a lot for your reply, especially on caching. I liked the comment earlier and was hoping to get back to it.

Other than when you use react-apollo, which other libraries do you use for caching in non Apollo projects?

Thread Thread
 
gaels profile image
GaelS

With classic rest API, there are several strategies to deal with caching.

1) You can have a REST API providing a cache-Control in its HTTP headers to help the browser to minimize server round-trips when possible (an interested link on the subject). It's a good one since few to no work is required on the front-end side.

2) You can have a reverse proxy on your back-end to filter incoming requests and use cache when possible. You do not save bandwidth but at least, you release the server's load.

3) However, if you are not in charge of the API but you still want to have a caching method, a naive way of doing it is to use memoization. Just a big word to describe a function that can save the results of its computation. Therefore, if it's called twice with the same arguments, the second call costs no compute time.

You can achieve this using closure in javascript.

Let's say you use axios to query whatever API you want with an id as an argument (mind that it's kind of a pseudo code - it won't run as is) :


function request() {

  // our cache is a simple
  // object here
  let cache = {};

  return async function(id){

    //if the cache has an "id" value
    // one returns it immediately
    if(cache[id]){
      return cache[id]
    }

    //the actual query
    //to the server
    const results = await axios.get(`${MY_API_URL}/${id}`);

    //one caches the value for future uses
    cache[id] = results;

    return results;
  }
}

Obviously, it's a very very very naive implementation which would require additional work to deal with expire dates, invalidation of the cache if a mutation is sent to the server for instance and so on. But I hope you'll get the idea of how the subject could be tackled :)

Thread Thread
 
joshuaai profile image
Josh Ihejiamaizu

I definitely do. This has sure come in handy, and just cycling back to say thank you.

Thread Thread
 
gaels profile image
GaelS

long shot but react-query is the go-to now ;)

Collapse
 
jokingzhang profile image
zhangboxuan

Hey man! This article is awesome, I am currently learning React. I have a problem, I have a list page, and a detail page, when I use history.goBack() on the detail page to return to the list page, the list page is refreshed and does not maintain the previous state. I found a solution through your article. Can I translate your article, learn, and then put it on the China Programming Forum website like Stack Overflow? Website Addr: segmentfault.com/

Collapse
 
gaels profile image
GaelS

Sure thing ! Awesome that it helps you ! :)

Collapse
 
peterjacobson profile image
Peter Jacobson

Thanks Gael, Really enjoyed your walkthrough - delightful and enlightening! btw love your miami vice styling!

Collapse
 
askshinde profile image
Gurubilli Shrinivas Reddy

Hello Sir, I have gone thru your demo search app. UI looks very nice. I have also created same app for one of my project, now the issue is if I do couple of searches and go back the search result doesnot change though the url param changes. This same issue I have seen in your app too. Any idea how to resolve this

Collapse
 
jokingzhang profile image
zhangboxuan

Hey, I translated your article into Chinese. This is the article link: segmentfault.com/a/1190000019364821 , thank you again!

Collapse
 
gaels profile image
GaelS

Awesome ! :D

Collapse
 
jzhou3900 profile image
jzhou3900

Hi, this is very helpful with my search form back and forth. How do you pass multiple query parameters? I have search form with one input textbox, one checkbox, now I can only update one parameter, either input box or checkbox, not both, ie. myapi/?keyword=test&checkbox=null. How to update state for multiple params in setParams function because you only can get one component state? Thanks.

Collapse
 
acomito profile image
acomito

URLs are a great strategy

Collapse
 
asmyshlyaev177 profile image
Alex

Can use existing library for this npmjs.com/package/state-in-url , for don't reinvent the wheel.