hitchhiker
hitchhiker

Reputation: 1319

Are eslint warnings for missing dependencies in React hooks always correct?

I'm wondering if eslint rule for mising dependencies in React hooks is always correct. In my example I have calendarIds object in the state. When the query is current-day I initialize the calendarIds object to some data. If the page query params change from curent-day to something else I want to reset the calendarIds object:

const {calendarData, query} = props
  useEffect(() => {
    console.log('useeffect2');
    if (query['date-range'] === 'current-day') {
      const [currentDay = { events: [] }] = calendarData;
      const events = currentDay.events.reduce((acc, { calendarId, actual, trend }) => {
          acc[calendarId] = { actual: actual || Math.round(Math.random() * 1000),
            trend };
          return acc;
      }, {});

      console.log(CALENDAR_IDS, 'events', events);
      setState({
        type: CALENDAR_IDS,
        payload: events
      });
    } else if (state.realTimeData.calendarIds) {
      setState({
        type: CALENDAR_IDS,
        payload: {}
      });
    }
  }, [calendarData, query]);

The dependencies array includes calendarData and query which trigger the function. In the else if I check if I have the calendarIds in the state already, if yes I reset it.

As a result I get a missing dependency for state.realTimeData.calendarIds. However I don't see why this would be a problem to not include it in the dependencies array. On the contrary, it may even trigger an infinite loop of state updates.

Upvotes: 1

Views: 142

Answers (1)

FranklinOcean
FranklinOcean

Reputation: 106

Your useEffect is depending on state.realTimeData.calendarIds being defined which is why you're getting that warning. You're using value outside of the useEffect context. You're also overriding your state.realTimeData.calendarIds data with your setState; not sure if that's intentional. An easy fix is to use a ref for the conditional, so you can rely on not causing an infinite loop.

Upvotes: 1

Related Questions