React Hook useEffect has a missing dependency: 'i18n'

111 Views Asked by At

I listen to languageChanged event of i18 in useEffect:

useEffect(() => {
  const onLanguageChange = () => {
    // setLanguageChanged(true)
  }

  i18n.on('languageChanged', onLanguageChange)

  return () => {
    i18n.off('languageChanged', onLanguageChange)
  }
}, [])

and get the warning:

ESLint: React Hook useEffect has a missing dependency: 'i18n'.

I don't want to ignore this warning by use eslint-disable.

Should I update the dependencies array to [i18n]? Or is there any other way?

1

There are 1 best solutions below

0
On

You don't have many options here, short of removing react-hooks/exhaustive-deps linting rule completely.

  • You can either ignore the missing dependency by selectively disabling the react-hooks/exhaustive-deps rule for that line:

    useEffect(() => {
      const onLanguageChange = () => {
        // setLanguageChanged(true)
      };
    
      i18n.on('languageChanged', onLanguageChange);
    
      return () => {
        i18n.off('languageChanged', onLanguageChange);
      };
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);
    
  • You can just add the missing dependency i18n:

    useEffect(() => {
      const onLanguageChange = () => {
        // setLanguageChanged(true);
      };
    
      i18n.on('languageChanged', onLanguageChange);
    
      return () => {
        i18n.off('languageChanged', onLanguageChange);
      };
    }, [i18n]);