In the react component below I want to display the current value of a url query param after updating it. Something like this is straightforward to do with react-router, but I am trying to implement manually in a more minimal app. The code below effectively updates the url, but does not trigger a re-render, so the displayed value never updates.
export default function ExampleComponent() {
const params = new URLSearchParams(location.search);
const randomValue = params.get("random");
function updateRandomValue() {
const updatedValue = Math.random().toString();
const newURL = new URL(location.href);
newURL.searchParams.set("random", updatedValue);
history.pushState("", "", newURL);
}
return (
<>
<p>random value is {randomValue || "none"}</p>
<button onClick={updateRandomValue}>update new random value</button>
</>
);
}
Am I handling the navigation wrong? Does there need to be a useEffect
involved somehow? Is this functionality impossible without an outer component and/or some use of react state?
2
Answers
Figured it out after a little more noodling. Still need to get a better handle on the why, but changing the click handler from my original snippet to below resolves the bug, without needing additional state:
I think you would need to use
useEffect
with a state dependency. Maybe something like:and then
<p>random value is {urlParam}</p>