L
L
lexstile2021-09-28 21:16:56
React
lexstile, 2021-09-28 21:16:56

What to do with the linter error and what are the best dependencies to include for useEffect?

The code:

useEffect(() => dispatch(initialPayouts({ userId, filter })), [filter]);

Mistake:
React Hook useEffect has missing dependencies: 'dispatch' and 'userId'. Either include them or remove the dependency array. (eslintreact-hooks/exhaustive-deps)


Do I need to include userId dependencies? (it does not change throughout the use of the application)
Do I need to include dispatch in the dependencies? Why?

If a filter is enough, how can you get around the error without crutches like a comment for a linter?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2021-09-28
@lexstile

Pretty controversial topic. There was a discussion on the github where Den exhorted everyone to forget about "componentDidMount" and think in terms of dependencies - since the component is essentially a reflection of the current state.
In your case, nothing changes, so you just need to add these values ​​to deps and not bother. The dispatcher is always constant, so turn it on too.
Actually, a problem can arise if you are only interested in the value at the time of the mount and you deliberately do not want to have an effect when changing. Then you can simply do, for example, const firstValue = useRef(propValue).current; , then in firstValue you will only have the first value that can be passed to useEffect. This is also a crutch, but more explicit code than ifnt-disable.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question