Introduction
In this lab, we will work with the useSearchParam hook which tracks the browser's location search param. This hook allows us to get the current value of a specified parameter in the URL and update it dynamically when the URL changes. By the end of this lab, you will have a better understanding of how to use this hook in your React applications to handle URL parameters.
React useSearchParam Hook
index.htmlandscript.jshave already been provided in the VM. In general, you only need to add code toscript.jsandstyle.css.
To track the browser's location search param, use the following steps:
- Create a callback using the
useCallback()hook. The callback should use theURLSearchParamsconstructor to get the current value of the desired parameter.
const getValue = React.useCallback(
() => new URLSearchParams(window.location.search).get(param),
[param]
);
- Create a state variable that holds the current value of the parameter using the
useState()hook.
const [value, setValue] = React.useState(getValue);
- Set appropriate event listeners to update the state variable when mounting and clean them up when unmounting using the
useEffect()hook.
React.useEffect(() => {
const => {
setValue(getValue());
};
window.addEventListener("popstate", onChange);
window.addEventListener("pushstate", onChange);
window.addEventListener("replacestate", onChange);
return () => {
window.removeEventListener("popstate", onChange);
window.removeEventListener("pushstate", onChange);
window.removeEventListener("replacestate", onChange);
};
}, []);
Here's an example of how to use this custom hook in a component:
const MyApp = () => {
const post = useSearchParam("post");
return (
<>
<p>Post param value: {post || "null"}</p>
<button =>
history.pushState({}, "", location.pathname + "?post=42")
}
>
View post 42
</button>
<button => history.pushState({}, "", location.pathname)}>
Exit
</button>
</>
);
};
ReactDOM.createRoot(document.getElementById("root")).render(<MyApp />);
This example creates a MyApp component that uses the useSearchParam custom hook to track the value of the post parameter in the location search. The post value is displayed in a paragraph tag. Two buttons are also included to demonstrate how to change the location search parameter value.
Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.
Summary
Congratulations! You have completed the React useSearchParam Hook lab. You can practice more labs in LabEx to improve your skills.