DEV Community

Cover image for react-router: useHistory, useLocation and useParams
Raynaldo Sutisna
Raynaldo Sutisna

Posted on

react-router: useHistory, useLocation and useParams

Introduction

I expect that you have read my previous blog, so you already know what is the three route props. If you don't know about it, check my previous blog here. I discuss how we can pass the three route props, and I want to show you another easy way to access it without thinking to pass as props.

useHistory

Basically, this hook gives you access to history objects and you have access to several functions to navigate your page. It's all about navigation. This is how you can use useHistory.

import { useHistory } from 'react-router-dom';

const Portfolio = (props) => {
    const history = useHistory();
    console.log(history);

    return (
        <div>
            Portfolio
        </div>
    );
};

export default Portfolio;
Enter fullscreen mode Exit fullscreen mode

What's inside history?

history object

Okay... so many things here. I know it is confusing in the beginning. I will explain the most common uses of these attributes.

  • length(number): the length of the page that you visited.
  • action(string): (POP, PUSH, REPLACE)
    • POP: Visiting the route via url, Using history go function(history.goBack(), history.goForward(), history.go())
    • PUSH: Using history.push()
    • REPLACE: using history.replace()
  • .push(pathname: string, state: any)/(location: object): push a path or location to the history stack. There are several ways to use push, and I show the examples below.
    //using pathname
    history.push("/blog");
    //https://localhost:3000/blogs

    //using pathname and state
    history.push("/blog", { fromPopup: true });
    //https://localhost:3000/blogs

    //using location
      history.push({
      pathname: "/blogs",
      search: "?id=5",
      hash: "#react",
      state: { fromPopup: true }
    });
    // https://localhost:3000/blogs?id=5#react
Enter fullscreen mode Exit fullscreen mode

I have never utilized the state before. However, after I read the documentation, the documentation gave me an idea. For example, if you want to know where the user came from, you can utilize the state.

  • .replace(pathname: string, state: any)/(location: object): this is basically similar to push, but it will remove the existing history and update to the new one. Whenever the user clicks back in the browser after .replace, it will not go back to the previous one.
  • .goBack(): move back to the previous history.
  • .goForward(): move forward to the previous history.
  • .go(delta: number): move to a different index and can specify how many indexes from this position (can be minus or positive)

I have never used the three go function, but I just want to let you know that this function has existed in history

I also prepare codesandbox to help you understand.

useLocation

Briefly, this is like a state that always returns your current URL. If the URL is changed, the useLocation will be updated as well.

What's inside location?

uselocation

useLocation doesn't have any function like useHistory, and it is just to grab information about your current URL.

I will use the previous link that we tried to use .push from history in the example localhost:3000/blogs?id=5#react.

from that URL, if we are trying to call useLocation, we will get this object.

uselocation2

Just keep in mind the purpose useLocation() is getting information from the current route, and it will return these attributes.

{
  key: 'ac3df4', // not with HashHistory!
  pathname: '/somewhere',
  search: '?some=search-string',
  hash: '#howdy',
  state: {
    [userDefined]: true
  }
}
Enter fullscreen mode Exit fullscreen mode

useParams

This is the easiest hook from react-router to understand. Whenever you call this hook you will get an object that stores all the parameters as attributes.

You just need this line of code and you can have access to your params.

const params = useParams();
Enter fullscreen mode Exit fullscreen mode

you can play around in my CodeSandBox

Conclusion

I hope this post could help you to understand the three main useful hooks from react-router. It is confusing in the beginning, but after I play around with it, everything makes sense and understandable. Enjoy playing react-router! post your comments to ask me questions.

Top comments (4)

Collapse
 
raaynaldo profile image
Raynaldo Sutisna

Hey thanks for leaving a comment here. I'm glad you understand a bit more after reading my post :) good luck for your learning

Collapse
 
ziyoweb profile image
Muhriddin Ziyodulloyev

very useful, thank you

Collapse
 
edward99vn profile image
edward99vn

Hi Raynaldo,
In my case, after pushing with state to another component, I click on go back button (history.goBack()) then state attribute in location will be lost. Do we have any ideas about that? Because I rely on state attribute in location to call API and load list.
Thank you!

Collapse
 
raaynaldo profile image
Raynaldo Sutisna

Hey @edward99vn, sorry for the late response. I'm not really sure about how react-router handle the state, but I think that make sense, we lose the state because we are not in the url anymore. I'm not sure if it's a good ide to rely on react-router state. Do you think you can use another state or redux?