DEV Community

Cover image for Remix JS: Sending state on redirect without using parameters
Leo Miranda
Leo Miranda

Posted on

Remix JS: Sending state on redirect without using parameters

Working with Remix means working with web standards. Just as we use search params to send data to another URL, we can also use a native browser feature, without exposing the information in the URL.

We will use the following hooks:

* You can use the Link component too, instead of useNavigate.


Problem to solve

I am implementing a Save As button, when it is clicked, I need to redirect to a new route with the new ID.

When opening the new cloned content, I want to show a message to the user.


Redirecting with state

After processing the data on the server side with the action function, we can validate the actiondData and create a redirect using the useNavigate hook.

Use option.state to send the state to the landing link.



const navigate = useNavigate();

...

navigate('your/path/here', {
  state: {
    message: 'successfully-copied',
  },
});


Enter fullscreen mode Exit fullscreen mode

Get the state in the landing page

Now, after being redirected to a new page, get the state using the useLocation hook.



const location = useLocation();
const stateMessage = location?.state?.message;


Enter fullscreen mode Exit fullscreen mode

See a real example using toast:



useEffect(() => {
  if (stateMessage) {
    toast.success(t(stateMessage), {
      id: stateMessage,
    });
  }
}, [stateMessage, creative]);


Enter fullscreen mode Exit fullscreen mode

Using the Link component instead of the useNavigate hook

You can also use the Link component to pass the state, instead of the useNavigate hook:

https://remix.run/docs/en/main/components/link#state


Under the hood

Under the hood we have the History interface of the History API, allowing manipulation of the browser session history. Simple, right?

History: state property:
https://developer.mozilla.org/en-US/docs/Web/API/History/state

Using Dev Tools console to update history api

That's it, Remix is simple and it uses web standards to the fullest.

And you? Do you like working with states differently? Tell us in the comments!

Top comments (0)