Home > Software engineering >  Using `useLocation().search` in useEffect without infinite loop
Using `useLocation().search` in useEffect without infinite loop

Time:03-08

I can't figure out a way to use query inside of useEffect without an infinite loop.

const query = new URLSearchParams(useLocation().search);

useEffect(() => {
  query.forEach((value, field) => {
    ...
  }
 }, [query]);

Any ideas?

CodePudding user response:

You're creating a new instance of URLSearchParams on every render (which is an object type and therefore has a different identity on each render), so the useEffect will run on every render (causing an infinite loop if the useEffect triggers a rerender).

Instead you can either move the definition of query into a useMemo call or just define query in the useEffect if it's not used elsewhere.

For example:

const { search } = useLocation();

const query = useMemo(() => new URLSearchParams(search), [search]);

useEffect(() => {
  query.forEach((value, field) => {
    ...
  }
 }, [query]);

or

const { search } = useLocation();

useEffect(() => {
  const query = new URLSearchParams(search);
  query.forEach((value, field) => {
    ...
  }
 }, [search]);
  • Related