Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[docs] jsx-no-bind: add section about React Hooks #2443

Merged
merged 1 commit into from Oct 4, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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.