Skip to content

Commit

Permalink
[docs] jsx-no-bind: add section about React Hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
kdex authored and ljharb committed Oct 3, 2019
1 parent fb3210b commit c739c9e
Showing 1 changed file with 30 additions and 1 deletion.
31 changes: 30 additions & 1 deletion docs/rules/jsx-no-bind.md
Expand Up @@ -37,7 +37,7 @@ When `true` the following are **not** considered warnings:
```jsx
<div onClick={this._handleClick.bind(this) />
<span onClick={() => console.log("Hello!")} />
<button onClick={function() { alert("1337") }} />
<button type="button" onClick={function() { alert("1337") }} />
```
### `ignoreRefs`
Expand Down Expand Up @@ -151,6 +151,35 @@ class Foo extends React.Component {
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).
### React Hooks
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:
```jsx
const onClick = () => {
console.log("Independent callback");
};
const Button = () => {
return (
<button type="button" onClick={onClick}>Label</button>
);
};
```
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:
```jsx
const Button = () => {
const [text, setText] = useState("Before click");
const onClick = useCallback(() => {
setText("After click");
}, [setText]); // Array of dependencies for which the memoization should update
return (
<button type="button" onClick={onClick}>{text}</button>
);
};
```
## When Not To Use It
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 comments on commit c739c9e

Please sign in to comment.