1.0.2 • Published 10 months ago

use-shallow v1.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
10 months ago

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-shallow

And 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();
  • queries is of type URLSearchParams and it holds the search parameters of the url To get the value of search in a url /blog?search=whatever

    you can use

    queries.get("search");

    Well, you can use whatever props and methods are available in the URLSearchParams object.

  • push is 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.

1.0.2

10 months ago

1.0.1

10 months ago

1.0.0

10 months ago