ensure-use-callback-has-non-empty-deps
Rule category
Pedantic.
What it does
Warns when useCallback
is called with empty dependencies array.
Why is this bad?
React Hooks useCallback
has empty dependencies array like what’s in the examples, are unnecessary. The hook can be removed and it’s value can be created in the component body or hoisted to the outer scope of the component.
Examples
Failing
import React, { function useCallback<T extends Function>(callback: T, deps: React.DependencyList): T
`useCallback` will return a memoized version of the callback that only changes if one of the `inputs`
has changed.useCallback } from "react";
function function Example(): React.JSX.Element
Example() {
// @warn: useCallback has empty dependencies array
const const onClick: () => void
onClick = useCallback<() => void>(callback: () => void, deps: React.DependencyList): () => void
`useCallback` will return a memoized version of the callback that only changes if one of the `inputs`
has changed.useCallback(() => {
var console: Console
console.Console.log(...data: any[]): void
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log("clicked");
}, []);
return <JSX.IntrinsicElements.button: React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>
button React.ButtonHTMLAttributes<HTMLButtonElement>.type?: "button" | "submit" | "reset" | undefined
type="button" React.DOMAttributes<HTMLButtonElement>.onClick?: React.MouseEventHandler<HTMLButtonElement> | undefined
onClick={const onClick: () => void
onClick} />;
}
Passing
import React from "react";
function function onClick(): void
onClick() {
var console: Console
console.Console.log(...data: any[]): void
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log("clicked");
}
function function Example(): React.JSX.Element
Example() {
return <JSX.IntrinsicElements.button: React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>
button React.ButtonHTMLAttributes<HTMLButtonElement>.type?: "button" | "submit" | "reset" | undefined
type="button" React.DOMAttributes<HTMLButtonElement>.onClick?: React.MouseEventHandler<HTMLButtonElement> | undefined
onClick={function onClick(): void
onClick} />;
}