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?
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With