title: How to detect route changes using React Router in React?
body: <p>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, <em>I want to reset the search: clear the results and the search input field</em>.</p>
  <p>Currently, I am handling this with a <code>Context</code>; I have a <code>SearchContext.Provider</code> that broadcasts the <code>resetSearch</code> function, and wherever I am handling navigation, I have consumers that invoke <code>resetSearch</code> before processing navigation (which I do programmatically with the <code>useHistory</code> hook).</p>
  <p>This doesn't work for back button presses on the browser's controls (since that is something out of my control).</p>
  <p>Is there an intermediate step before my <code>Routes</code> are rendered (or any browser navigation happens) that I can hook into, to make sure my <code>resetSearch</code> function is invoked?</p>
  <p>As requested, here is the code:</p>
  <pre><code>// App.js
  const [query, setQuery] = useState(&quot;&quot;);
  const [results, setResults] = useState([]);
  
  const resetSearch = () =&gt; {
      setResults([]);
      setQuery(&quot;&quot;);
  };
  
  &lt;SearchContext.Provider value={{ resetSearch }}&gt;
      // all of my &lt;Route /&gt; components in this block
  &lt;/SearchContext.Provider&gt;
  </code></pre>
  <pre><code>// BusRoute.js
  const { resetSearch } = useContext(SearchContext);
  
  const handleClick = stop =&gt; {
      resetSearch();
      history.push(`/stops/${stop}`);
  };
  
  return (
      // some other JSX
      &lt;button onClick={() =&gt; handleClick(stop.code)}&gt;{stop.name}&lt;/button&gt;
  );
  </code></pre>