React useSearchParam Hook

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react(("`React`")) -.-> react/AdvancedConceptsGroup(["`Advanced Concepts`"]) react(("`React`")) -.-> react/StateManagementGroup(["`State Management`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/FundamentalsGroup -.-> react/event_handling("`Handling Events`") react/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") react/StateManagementGroup -.-> react/use_state_reducer("`Using useState and useReducer`") subgraph Lab Skills react/jsx -.-> lab-38407{{"`React useSearchParam Hook`"}} react/event_handling -.-> lab-38407{{"`React useSearchParam Hook`"}} react/hooks -.-> lab-38407{{"`React useSearchParam Hook`"}} react/use_state_reducer -.-> lab-38407{{"`React useSearchParam Hook`"}} end

React useSearchParam Hook

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.css.

To track the browser's location search param, use the following steps:

  1. Create a callback using the useCallback() hook. The callback should use the URLSearchParams constructor to get the current value of the desired parameter.
const getValue = React.useCallback(
  () => new URLSearchParams(window.location.search).get(param),
  [param]
);
  1. Create a state variable that holds the current value of the parameter using the useState() hook.
const [value, setValue] = React.useState(getValue);
  1. Set appropriate event listeners to update the state variable when mounting and clean them up when unmounting using the useEffect() hook.
React.useEffect(() => {
  const onChange = () => {
    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
        onClick={() =>
          history.pushState({}, "", location.pathname + "?post=42")
        }
      >
        View post 42
      </button>
      <button onClick={() => 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.

Other React Tutorials you may like