4

Let's say that we have a React application with an entrypoint that looks like this:

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';

import Application from './Application';


ReactDOM.render((
    <BrowserRouter>
        <Application />
    </BrowserRouter>
), document.getElementById('root'));

Somewhere deep in the React application, I'd like to add (or update) query parameters in response to some user action. I could use the history.push() method which react-router provides, but using that method causes Application to be re-rendered.

Is it possible to add or update query parameters without Application being re-rendered? I have found that I can change query parameters without Application being re-rendered if I use the History API directly, but this feels like a hack.

John Karahalis
  • 3,369
  • 2
  • 15
  • 20
  • Doesn't feel like a hack to me, feels like a viable solution. Wrapped history is there to re-render and I don't think they provide a silent option, that would be just unwrapped history imo. – Dominic Sep 28 '18 at 21:18
  • I think it's a hack because doing this causes react-router's `history` and `location` objects not to be updated. Those can be useful. I'm actually running into a situation right now where it would be useful to read from them. – John Karahalis Oct 04 '18 at 20:48

1 Answers1

0

I am currently reading a book about react and had the same issue.

What I found out is that you need to add shouldComponentUpdate method to the parent component and validate if the location.search value is different

this.props.location.search !== nextProps.location.search

Returning true from that validation will re-render the component

P.S. The book was using React Router v3 so I was having a hard time with the whole app being updated and the nested routes

P.P.S. I'm using history which now is a package outside of React Router

pakman198
  • 123
  • 6
  • In this example, `Application` does not have any props. But your broader point is correct: I could implement `shouldComponentUpdate` or make `Application` a `PureComponent`, which would prevent it from re-rendering until any props have changed. That might actually be a cleaner workaround than using the history API and I appreciate the suggestion. Still, I wonder if react-router has a way to change query params without re-rendering everything, in the same way the history API has a way to change query params without reloading. – John Karahalis Sep 29 '18 at 04:43