I am trying to initialize a state variable by assigning it the value of query/search parameter.
For example, if the full URL is http://localhost:3000/mycomponent?author=John
Then I would like to assign the value John
to my state variable named author
, like this:
const [author, setAuthor] = useState(useSearchParams().get("author") || "abc")
But abc
gets assigned to the state variable author
, instead of John
.
I guess useSearchParams() is not meant to be used where I am trying to use it.
Below is the full code:
import React from 'react';
import { useEffect, useState } from "react";
import { useSearchParams } from 'next/navigation';
function MyComponent() {
const searchParams = useSearchParams();
const [author, setAuthor] = useState(useSearchParams().get("author") || "abc");
return (
<div>
<h1>Search Results for: {author}</h1>
</div>
);
}
export default MyComponent;
I can assign the correct value to author
in useEffect
hook but useEffect runs after a slight delay, and because of that delay, the header initially shows up as Search Results for:
Then it changes to Search Results for: John
.
The delay isn't significant but noticeable.
You probably don't need to be making useSearchParams
into a state variable at all. State variables let you do things when React re-renders the component (after a state variable changes) ... but useSearchParams
will already re-render your component when it changes.
If you really did need to remember a previous search param and you need to re-render when it changes (again, unlikely), you could use a useEffect
to set the state variable ... but this almost certainly not what you want:
const searchParams = useSearchParams();
const [author, setAuthor] =
useState(searchParams.get("author") || "abc");
useEffect(() =>{
setAuthor(searchParams);
}, [searchParams]);
What you probably want is just a regular old JS variable:
const searchParams = useSearchParams();
const author = useSearchParams().get("author");
This will work just fine because author
gets updated every time the component re-renders (ie. whenever searchParams
or a state variable changes). This means it will always be equal to the author, without any need for state variables.