use-shallow
v1.0.2
Published
A tiny React hook for implementing shallow routing
Maintainers
Readme
useShallow Hook
Shallow routing
Shallow routing allows you to change the URL without running data fetching methods again.
for example when you want to do filtering with input that changes the url on each type
/blog?search=shallow
The Problem
If you used Next Js before you might noticed that in Next 12 there was a shallow routing functionality, but in the latest version (Next 13) shallow routing is no longer there.
The Solution
The useShallow React Hook is providing a workaround for that same functionality for both vanilla React and Next Js.
Installation
Install using npm :
npm install use-shallowAnd then import useShallow :
import useShallow from "use-shallow";NOTE !important
Adding a state is required even if it's not used in the component.
This state causes the component to re-render so it recognizes the updated url.
Usage
Its used like any other React hook
const [queries, push] = useShallow();queriesis of typeURLSearchParamsand it holds the search parameters of the url To get the value of search in a url/blog?search=whateveryou can use
queries.get("search");Well, you can use whatever props and methods are available in the
URLSearchParamsobject.pushis a function that allows you to change the url It takes one parameter which is the desired url you wanna route to. Example:push(`/blog?q=${searchQuery}`);
NOTE !important
In some cases (based on your usage) you may find that queries are getting the previous and not the current query.
For example if your url has ?query=React, but queries gets Reac instead of React.
For solving this issue, you may consider adding an extra state that causes re-render to get the current (latest) query.
