Raphael Rafatpanah
Raphael Rafatpanah

Reputation: 19967

React Router v5 - How to force a route to always re-render when location changes?

Consider this codesandbox example.

import React from "react";
import "./styles.css";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

const Foo = () => {
  console.log("rendered");
  return null;
};

export default function App() {
  return (
    <Router>
      <Route>
        <Foo />
      </Route>
      <div className="App">
        <Link to="/">Home</Link>
        <br />
        <Link to="/foo">Foo</Link>

        <Route path="/" exact>
          <p>Home</p>
        </Route>
        <Route path="/foo">
          <p>Foo</p>
        </Route>
      </div>
    </Router>
  );
}

Currently, when clicking on a <Link /> to change the location, the <Foo /> component never re-renders. How can we force a re-render when the location changes?

Upvotes: 1

Views: 2764

Answers (1)

Raphael Rafatpanah
Raphael Rafatpanah

Reputation: 19967

Using the useLocation hook that React Router provides works.

https://reactrouter.com/native/api/Hooks/uselocation

import { BrowserRouter as Router, Route, Link, useLocation } from "react-router-dom";

const Foo = () => {
  useLocation();
  console.log("rendered");
  return null;
};

Upvotes: 1

Related Questions