Managing UI state in location query

sanohin profile image Aleksandr Anokhin ・2 min read

I think every frontend developer had to store somewhere value of open dialog, selected tab etc.
For example, you have a simple requirement to open some small settings modal when a user clicks a button:

If you use React, then you are lucky, you've got component state:

openDialog = () => this.setState({ dialogOpen: true });

But then designer wants this dialog to open from few random components like here:

These two dropdowns are different components with different state and in one of them, we have our SettingsDialog component. So what should we do now?
Add SettingsDialog to the second dropdown, same openDialog state key, and handlers? Or we can go further and put handlers and state key to a HOC to reuse this functionality? If we use redux we can also create UI reducer or use it if we have. UI reducer is just a messy object with different key-value pairs that are used and changed from across the whole application in random places. Here is the most primitive implementation (however complete enough):

const ui = (state, action) => {
  if (action.type === "ui/set") {
    return { ...state, [action.key]: action.value };
  return state;

Though, we can improve this. Not everyone uses redux even. We can keep the state of open dialog in the URL like "http://my.app?openDialog=true".
If a user refreshes the page, he still would see the dialog open. It is especially essential when we keep the state of selected tab like:

But the best use case is probably of storing state in query is table filters and sort column. As a result, user would be able to share the same state he has.

So be flexible, keep state not only in your React components and redux.


Editor guide