Home > Enterprise >  React Router Dom, difference between passing id as url params or state
React Router Dom, difference between passing id as url params or state

Time:07-11

This is more of a poll than anything else. When working with React, do you pass parameters when routing by chaining them to the URL or as state?

Is there even a best practice to follow for this?

Params:

navigate('/edit/${user.id}')`

State:

navigate('/edit', { state : {id :user.id} } )

CodePudding user response:

For me, it depends on the action I am trying to do.

If I want a single route with some dynamic information, such as chat id, which I don't want to be stored in the URL, I prefer setting it in the history state.

But, for REST actions (edit/add and such on), I prefer chaining the id in the URL itself. It has some benefits. The primary one I see is that you can copy the URL, paste it somewhere else (different computer/browser), and you'll still access the same page with the details about the id you chained.

CodePudding user response:

This depends on what you prefer and what your project needs. The difference between the two is as follow:

  1. navigate('/edit', { state : {id :user.id} }) won't write the id in the url. And you consume it with the help of useLocation hook, this way:
import { useLocation } from "react-router-dom";
function Edit() {
 const { state } = useLocation();
 return (
  <div>
     {state.id}
   </div>
 );
}
export default Edit;

It's more flexible, as you can or not pass the id. For example you can pass it when you are navigating from login page, but not in other cases.

  1. navigate('/edit/${user.id}') would mean that you have defined a slug while setting up your route, like so:
<Route path = "/edit/:id" element= {<Edit/>}/>

And you consume it this time with useParmas hook:

import { useParams } from "react-router-dom";
function Edit() {
 const { id } = useParams();
 return (
  <div>
     {id}
   </div>
 );
}
export default Edit;

In the last case, the id should be there, all the time, to make a correct path.

  • Related