The (currently) accepted answer misses an important detail. When the component unmounts, the interval will keep running. To stop it, you need to clearInterval
. Another mistake is useEffect
is called without dependencies. Here we use useCallback
to generate a function that will only update when the id
updates. Both the callback and the id
are passed as dependencies to useEffect
-
const [data, setData] = useState(...)
const update = useCallback(id =>
fetch(`http://.../${id}/`)
.then(r => r.json())
.then(setData),
[id]
)
useEffect(() => {
const t = setInterval(_ => update(id), 5000)
return () => clearInterval(t)
}, [update, id])
In a related Q&A we introduce a custom useInterval
hook that makes it easy for components to work with interval-based state. See the post for a fully functioning code demonstration.