menu

Questions & Answers

Why isn't this React component updated when dependency changes?

I have this simple React component with a search bar, it gets the input value and navigates to an URL setting the input value as a query param. Once in the component, it gets the 'keyword' from the URL query params and calls an API to get results.

It only works the first time. But if I change the input value it doesn't update the 'keyword' variable value, even though the URL is properly updated.

Why isn't my variable updated?

export default function Resultados () {

    let keyword = new URLSearchParams(window.location.search).get('keyword')

    const apiKey = '123' ;

    useEffect(()=>{
        axios
            .get(`https://api.themoviedb.org/3/search/movie?api_key=${apiKey}&language=es-ES&query=${keyword}&page=1&include_adult=false
            `)
            .then(res=>{
                console.log(res.data)
            })

    },[keyword])

    return (
        <>
            <h2>Resultados de {keyword}</h2>
        </>
    )
}

I've included the keyword variable on the useEffect dependency array, but it seems the variable is not changing.

Comments:
2023-01-24 23:25:13
are u using react-router? when yes, u can use useSearchParams()
Answers(1) :

The dependency array to a useEffect will never cause your component to render. In fact, it's only useful if the component is already rendering, at which point it can skip the effect if nothing has changed. Instead, if you want the component to render, you must set state (either here or in some parent component).

So you either need to write custom code which detects when the url changes, and at that point set state; or you can use an existing routing library such as react-router or react-location, which have already written that code for you. For example, here's how you would do it in react-router:

import { useSearchParams } from 'react-router';

export default function Resultados () {
  const [searchParams] = useSearchParams();
  const keyword = searchParams.get('keyword');

  // rest of your code is the same
}
Comments:
2023-01-24 23:25:13
This worked using the useSearchParams hook. Thanks!