How to detect route changes using React Router in React?

Viewed 5544

I have a search component that is global to my application, and displays search results right at the top. Once the user does any sort of navigation, e.g., clicking a search result or using the back button on the browser, I want to reset the search: clear the results and the search input field.

Currently, I am handling this with a Context; I have a SearchContext.Provider that broadcasts the resetSearch function, and wherever I am handling navigation, I have consumers that invoke resetSearch before processing navigation (which I do programmatically with the useHistory hook).

This doesn't work for back button presses on the browser's controls (since that is something out of my control).

Is there an intermediate step before my Routes are rendered (or any browser navigation happens) that I can hook into, to make sure my resetSearch function is invoked?

As requested, here is the code:

// App.js
const [query, setQuery] = useState("");
const [results, setResults] = useState([]);

const resetSearch = () => {
    setResults([]);
    setQuery("");
};

<SearchContext.Provider value={{ resetSearch }}>
    // all of my <Route /> components in this block
</SearchContext.Provider>
// BusRoute.js
const { resetSearch } = useContext(SearchContext);

const handleClick = stop => {
    resetSearch();
    history.push(`/stops/${stop}`);
};

return (
    // some other JSX
    <button onClick={() => handleClick(stop.code)}>{stop.name}</button>
);
2 Answers

You can listen to history changes:

useEffect(() => {
  const unlisten = history.listen((location) => {
    console.log('new location: ', location)
    // do your magic things here
    // reset the search: clear the results and the search input field
  })
  return function cleanup() {
    unlisten()
  }
}, [])

You can use this effect in your parent component which controls your global search's value.

You can use componentWillUnmount feature from class components with useEffect in hooks with functional component

Related