By default, React assumes that every effect that is run needs to be cleaned up. This typically isn't the case. For example, you might have specific property or state values that require cleanup when they change. You can pass an array of values to watch as the second argument to useEffect(). For example, if you have a resolved state that requires cleanup when it changes, you would write your effect code like this:
const [resolved, setResolved] = useState(false);
useEffect(() => {
// ...the effect code...
return () => {
// ...the cleanup code that depends on "resolved"
}
}, [resolved]);
In this code, the cleanup function will only ever run if the resolved state value changes. If the effect runs and the resolved state hasn't changed, then the cleanup code will not run. Another common case is to never run the cleanup code, except for when the component is removed. In fact, this is what we want to happen in the example from...