Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Hooks: Make useEffect run when location.search changes

I am trying to make a useEffect fire every time the query params of my URL changes, this is the format of the URL:

https://localhost:3000/main/persons?results=1

In my code I have the following:

const location = useLocation();

useEffect(() => {
      console.log('Location update')
    }, [location]);

However, my problem is that the useEffect is only run when the location.pathname changes, and not when the query parameters of the URL changes (?results=1). I have also tried the following logic: [location.pathname, location.search] but with no luck.

Do anyone know how I can solve this?

like image 403
alp123 Avatar asked Jun 29 '26 10:06

alp123


2 Answers

Try doing this:

const { pathName } = useLocation();

useEffect(() => {
    console.log('Location update')
}, [pathName]);

Similarly for location.search

like image 58
Sakshi Avatar answered Jul 01 '26 21:07

Sakshi


For URL params use useParams in your hook

let { results} = useParams();

useEffect(() => {
      console.log('Params updated',results)
    }, [results]);
like image 37
Sanoodia Avatar answered Jul 01 '26 22:07

Sanoodia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!