How to handle ESLint react-hooks 'exhaustive-deps' rule when using i18next?

Viewed 66

I have add react-hook/exhaustive-deps and Im having issues deciding how to do things.

Let's say that I have a function that does an Ajax call to get user data. If there is an error then it informs the user about it.

const { t } = useTranslation();
const [textErrorKey, setTextErrorKey] = useState();
useEffect(() => {
  async function getUser() {
     setLoading(true);
     try {
       const { user } = await queryUser(userId);
       setUser(user);
     } catch(error) {
       setLoading(false);
       if(!error.isAuthenticated) {
         setTextErrorKey(t('not-authenticated'));
       }
     }
  }
  
  if (id) {
    getUser();
  }
}, [t, id])

When the user decides to change the language, Does it mean that it will execute this code again ? How can I avoid that ? I don't want a second Ajax call because the language has changed.

I know that I can disable the rule but Im reading everywhere that it is more convenient not to do it. Is there any best practices or blog post related to handling common uses cases for react-hook/exhaustive-deps ?

1 Answers

I guess that I could do the evaluation on every render without getting penalty:

const [textErrorKey, setTextErrorKey] = useState();
const { t } = useTranslation();

// Takes care of loading data when 'id' changes
useEffect(() => {
  async function getUser() {
     setLoading(true);
     try {
       const { user } = await queryUser(userId);
       setUser(user);
     } catch(e) {
       if(!e.isAuthenticated) {
         setTextErrorKey('not-authenticated'));
       }
     } finally {
       setLoading(false);
     }
  }
  
  if (id) {
    getUser();
  }
}, [id])

return (
  <div>
    {user?.name ?? t(textErrorKey)}
  </div>
)

The react team has elaborate a proposal that address this type of issues: https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md

They have come together to have a new hook called useEvent. Not in react yet.

Related