diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d08a7762a..6c2fc9b793 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,10 @@ This change log adheres to standards from [Keep a CHANGELOG](http://keepachangel ### Fixed * component detection: use `estraverse` to improve component detection ([#2992][] @Wesitos) +### Changed +* [Docs] [`jsx-no-bind`]: updates discussion of refs ([#2998][] @dimitropoulos) + +[#2998]: https://github.com/yannickcr/eslint-plugin-react/pull/2998 [#2992]: https://github.com/yannickcr/eslint-plugin-react/pull/2992 ## [7.24.0] - 2021.05.27 diff --git a/docs/rules/jsx-no-bind.md b/docs/rules/jsx-no-bind.md index d7335ed182..fe7833a3c7 100644 --- a/docs/rules/jsx-no-bind.md +++ b/docs/rules/jsx-no-bind.md @@ -2,6 +2,8 @@ A `bind` call or [arrow function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) in a JSX prop will create a brand new function on every single render. This is bad for performance, as it may cause unnecessary re-renders if a brand new function is passed as a prop to a component that uses reference equality check on the prop to determine if it should update. +Note that this behavior is different for `ref` props, which is a special case in React that **does not** cause re-renders when a brand new function is passed. See [`ignore-refs`](#ignorerefs) below for more information. + ## Rule Details Examples of **incorrect** code for this rule: @@ -42,10 +44,19 @@ Examples of **correct** code for this rule, when `ignoreDOMComponents` is `true` ### `ignoreRefs` +Refs are a special-case that do not behave like other props. Sending a new function in on ever render will **not** cause re-renders like it could with any other prop. + +However, there is a [caveat with callback refs](https://reactjs.org/docs/refs-and-the-dom.html#caveats-with-callback-refs): +> If the ref callback is defined as an inline function, it will get called twice during updates, first with null and then again with the DOM element. This is because a new instance of the function is created with each render, so React needs to clear the old ref and set up the new one. You can avoid this by defining the ref callback as a bound method on the class, but note that it shouldn’t matter in most cases. + +You can also avoid this behavior using [`createRef`](https://reactjs.org/docs/react-api.html#reactcreateref) or [`useRef`](https://reactjs.org/docs/hooks-reference.html#useref) (or [`useCallback`](https://reactjs.org/docs/hooks-reference.html#usecallback) if you have custom logic). + +If you are using a simple setter (as shown below) then you may not need this rule to fire for `ref`s, and can disable it specifically for refs with `ignoreRefs`. + Examples of **correct** code for this rule, when `ignoreRefs` is `true`: ```jsx - this._div = c} /> + { this._div = ref; }} /> ```