Search code examples
reactjseslinteslint-plugin-react-hooks

useEffect and ESlint exhaustive-deps rule


I'm currently stuck on how to build my logic without having any warning about exhaustive-deps in my useEffect.

My goal is to track navigation (enter page date, leave page date and location) on location change.

I am using useLocation() of react-router-dom and useLastLocation() of react-router-last-location.

const location = useLocation()
const lastLocation = useLastLocation()

const [date, setDate] = React.useState(new Date())

React.useEffect(() => {
  const end = new Date()
  API.sendData({ start: date, end, location: lastLocation })
  setDate(end)
}, [location, lastLocation])

This is working fine but my useEffect dependencies array should contains date to not have exhaustive-deps warning, but adding it, will make infinite loops.

What is the correct way to do it ?


Solution

  • The useState dispatch also allows you to provide a function that accepts the current value as an argument rather than simply a value. That way you could avoid the date as a dependency.

    const location = useLocation()
    const lastLocation = useLastLocation()
    
    const [date, setDate] = React.useState(new Date())
    
    React.useEffect(() => {
      setDate((currentDate) => {
        const end = new Date();
        API.sendData({ start: currentDate, end, location: lastLocation });
        return end;
      });
    }, [location, lastLocation]);