Alfrex92
Alfrex92

Reputation: 6778

Cleanup Function in useEffect using Typescript

I'm using React Typescript and I have the following warning:

warning Missing return type on function

This is my code:

 useEffect(() => {
    window.addEventListener('scroll', fetchAllFriends, { once: true })

    return () => {
      window.removeEventListener('scroll', fetchAllFriends)
    }
  }, [fetchAllFriends])

Does that mean that we need a return (): void on every cleanup function inside useEffect?

Upvotes: 2

Views: 2716

Answers (1)

wentjun
wentjun

Reputation: 42526

The reason why the above warning is happening is probably because you have activated following ESLint rule:

@typescript-eslint/explicit-function-return-type

To answer your question, you can set the return type as void.

Alternatively, you can turn the above rule off, as you don't always have to explicitly set the return type of all of your methods as TypeScript can usually infer the return types based on what is returned on the method. Personally, I turn it off for most of my projects.

getUser() {
  return service.getUser();
}

For instance, with the above scenario, TypeScript should be able to infer the return type without the need the specify the return type.


EDIT: as mentioned by @paolostyle in the comments, if you wish to keep the rule, but disable the rule for your scenario, you can toggle the allowExpressions option and set it to true.

"@typescript-eslint/explicit-function-return-type": ["error", {
  "allowExpressions": true,
}]

Upvotes: 2

Related Questions