Skip to content

Commit c739c9e

Browse files
kdexljharb
kdex
authored andcommitted
[docs] jsx-no-bind: add section about React Hooks
1 parent fb3210b commit c739c9e

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

docs/rules/jsx-no-bind.md

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ When `true` the following are **not** considered warnings:
3737
```jsx
3838
<div onClick={this._handleClick.bind(this) />
3939
<span onClick={() => console.log("Hello!")} />
40-
<button onClick={function() { alert("1337") }} />
40+
<button type="button" onClick={function() { alert("1337") }} />
4141
```
4242
4343
### `ignoreRefs`
@@ -151,6 +151,35 @@ class Foo extends React.Component {
151151
152152
A more sophisticated approach would be to use something like an [autobind ES7 decorator](https://www.npmjs.com/package/core-decorators#autobind) or [property initializers](https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding).
153153
154+
### React Hooks
155+
156+
Functional components are often used alongside hooks, and the most trivial case would occur if your callback is completely independent from your state. In this case, the solution is as simple as moving the callback out of your component:
157+
158+
```jsx
159+
const onClick = () => {
160+
console.log("Independent callback");
161+
};
162+
const Button = () => {
163+
return (
164+
<button type="button" onClick={onClick}>Label</button>
165+
);
166+
};
167+
```
168+
169+
Otherwise, the idiomatic way to avoid redefining callbacks on every render would be to memoize them using the [`useCallback`](https://reactjs.org/docs/hooks-reference.html#usecallback) hook:
170+
171+
```jsx
172+
const Button = () => {
173+
const [text, setText] = useState("Before click");
174+
const onClick = useCallback(() => {
175+
setText("After click");
176+
}, [setText]); // Array of dependencies for which the memoization should update
177+
return (
178+
<button type="button" onClick={onClick}>{text}</button>
179+
);
180+
};
181+
```
182+
154183
## When Not To Use It
155184
156185
If you do not use JSX or do not want to enforce that `bind` or arrow functions are not used in props, then you can disable this rule.

0 commit comments

Comments
 (0)