简体   繁体   中英

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?

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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM