Refs in useEffect in react-aria #7750
Replies: 2 comments 3 replies
-
They sometimes make their way in, eslint can't catch them all, but they shouldn't cause any harm. Is it causing an issue for you? |
Beta Was this translation helpful? Give feedback.
-
The reason why React libraries like react-aria might include refs (like scopeRef) in the dependencies array of useEffect or useLayoutEffect—even though they don’t trigger side effects directly—has to do with how React manages re-renders and ensures that the effect is correctly triggered in the right scenarios. Here’s why refs might be included: React and Refs: While React refs don't cause re-renders directly when updated, they still refer to mutable DOM elements. React doesn’t trigger re-renders when the current value of a ref changes, but it ensures that the effect hook runs whenever the ref itself changes. This can be important if the hook logic depends on the presence or state of the referenced DOM element. Ensuring Effect Execution: Including scopeRef in the dependencies of useLayoutEffect guarantees that the effect will run if the ref object itself changes. This is especially necessary if the library logic needs to track when the referenced DOM element (the scopeRef in this case) is either updated or reassigned. Even though changing the ref doesn’t directly trigger a re-render, the effect should still react to changes in the reference. Stabilizing Side Effects: In some cases, it’s important to make sure the effect is run again even if the reference itself hasn't changed but the DOM or the context in which it operates has. Including refs in the dependency array helps manage this behavior. Preventing Stale Closures: If the effect hook doesn’t depend on the latest ref, it could cause a stale closure, where the effect references an outdated version of the DOM element. Including refs in the dependency array ensures that the latest ref is always captured and avoids potential issues with stale closures. In your example: |
Beta Was this translation helpful? Give feedback.
-
guys why do libs like react-aria have refs in useEffect deps even though they don't trigger side effects?
Beta Was this translation helpful? Give feedback.
All reactions