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;

What's inside history?

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

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 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.

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
  }
}

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();

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.

19