Working with closures is something that can become quite tricky, especially when dealing with hooks that have dependencies in React (think useEffect,

Hooks, Dependencies and Stale Closures

submited by
Style Pass
2022-09-21 18:30:12

Working with closures is something that can become quite tricky, especially when dealing with hooks that have dependencies in React (think useEffect, useMemo, useCallback). A lot of bugs and frustration are tied pretty closely to that concept - even though it is nothing that React itself introduced. It's rather a language concept that hooks rely upon.

Question for the React community: Has the shift from "how does `this`/binding work?"-type questions to "why is my state stale due to closures?"-type questions made things better, worse, or just "same thing but different" ? (Inspired by the questions we see in @reactiflux daily)

To me, it has gotten subjectively better. Working with this in class components was a pain, and errors did mostly show up at runtime. However, the behaviour you get due to stale closures are more subtle, and come up in more edge cases. The big advantage though is that they can be statically analyzed - and that's exactly what the react-hooks/exhaustive-deps eslint rule does.

In this article, I'll try to break down what stale closures are, what they have to do with React and hooks, and why the lint rule is so important that I think you should set it to error. To get there, we must first understand what (stale) closures are:

Leave a Comment