What is the difference between using "useSearchParams" with suspense and this other hook?
Answered
Transvaal lion posted this in #help-forum
Transvaal lionOP
Another hook, alternative:
import { useEffect, useState } from "react";
export const useCustomSearchParams = () => {
const [queries, setQueries] = useState<URLSearchParams | []>([]);
useEffect(() => {
if (typeof window !== "undefined") {
const searchParams = new URLSearchParams(window?.location?.search);
setQueries(searchParams);
}
}, []);
return queries
};
import { useEffect, useState } from "react";
export const useCustomSearchParams = () => {
const [queries, setQueries] = useState<URLSearchParams | []>([]);
useEffect(() => {
if (typeof window !== "undefined") {
const searchParams = new URLSearchParams(window?.location?.search);
setQueries(searchParams);
}
}, []);
return queries
};
Answered by joulev
assume static rendering:
with
with
compared to static rendering, in dynamic rendering, you don't need
with
useSearchParams you replace the entire component using the hook with a loading component when the hook is not ready.with
useCustomSearchParams you have an incorrect initial value ([]) and you have to handle this case in the components consuming this hook.compared to static rendering, in dynamic rendering, you don't need
Suspense, useSearchParams will automatically work smoothly without requiring a loading component, while useCustomSearchParams still requires a loading state (incorrect initial value).1 Reply
@Transvaal lion Another hook, alternative:
import { useEffect, useState } from "react";
export const useCustomSearchParams = () => {
const [queries, setQueries] = useState<URLSearchParams | []>([]);
useEffect(() => {
if (typeof window !== "undefined") {
const searchParams = new URLSearchParams(window?.location?.search);
setQueries(searchParams);
}
}, []);
return queries
};
assume static rendering:
with
with
compared to static rendering, in dynamic rendering, you don't need
with
useSearchParams you replace the entire component using the hook with a loading component when the hook is not ready.with
useCustomSearchParams you have an incorrect initial value ([]) and you have to handle this case in the components consuming this hook.compared to static rendering, in dynamic rendering, you don't need
Suspense, useSearchParams will automatically work smoothly without requiring a loading component, while useCustomSearchParams still requires a loading state (incorrect initial value).Answer