问题描述
正如中所述,useCallback
返回一个memoized回调。
As said in docs, useCallbackReturns a memoized callback.
传递内联回调和一组输入。 useCallback将返回一个回忆的memoized版本,该版本仅在其中一个输入发生更改时才会更改。这在将回调传递给依赖于引用相等性的优化子组件以防止不必要的渲染时很有用(例如,shouldComponentUpdate)。
Pass an inline callback and an array of inputs. useCallback will return a memoized version of the callback that only changes if one of the inputs has changed. This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders (e.g. shouldComponentUpdate).
const memoizedCallback = useCallback(
() => {
doSomething(a, b);
},
[a, b],
);
但它如何运作以及在React中最好使用它?
But how does it work and where is the best to use it in React?
推荐答案
当你想要防止不必要的重新渲染以获得更好的性能时,最好使用它。
This is best used when you want to prevent unnecessary re-renders for better performance.
比较这两种方法将回调传递给从:
Compare these two ways of passing callbacks to child components taken from React Docs:
class Foo extends Component {
handleClick() {
console.log('Click happened');
}
render() {
return <Button onClick={() => this.handleClick()}>Click Me</Button>;
}
}
2。在构造函数中绑定(ES2015)
2. Bind in Constructor (ES2015)
class Foo extends Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log('Click happened');
}
render() {
return <Button onClick={this.handleClick}>Click Me</Button>;
}
}
假设< Button>
实现为 PureComponent
,第一种方式将导致< Button>
重新执行-render每次< Foo>
重新渲染,因为在每个 render()
调用中都会创建一个新函数。在第二种方式中, handleClick
方法仅在< Foo>
的构造函数中创建一次,并在渲染中重复使用。
Assuming <Button>
is implemented as a PureComponent
, the first way will cause <Button>
to re-render every time <Foo>
re-renders because a new function is created in every render()
call. In the second way, the handleClick
method is only created once in <Foo>
's constructor and reused across renders.
如果我们使用钩子将两种方法转换为功能组件,则这些是等价物(类型):
If we translate both approaches to functional components using hooks, these are the equivalents (sort of):
function Foo() {
const handleClick = () => {
console.log('Click happened');
}
return <Button onClick={handleClick}>Click Me</Button>;
}
2。在构造函数中绑定(ES2015) - >已记住的回调
2. Bind in Constructor (ES2015) -> Memoized callbacks
function Foo() {
const memoizedHandleClick = useCallback(
() => console.log('Click happened'), [],
); // Tells React to memoize regardless of arguments.
return <Button onClick={memoizedHandleClick}>Click Me</Button>;
}
第一种方法是在每次调用功能组件时创建回调,但在第二种方式中方式,React为你记忆回调函数,并且不会多次创建回调。
The first way creates callbacks on every call of the functional component but in the second way, React memoizes the callback function for you and the callback is not created multiple times.
在大多数情况下,第一种方式都可以。正如React docs所述:
In most cases, it's fine to do the first way. As the React docs state:
如果确实存在性能问题,请进行优化!
If you do have performance issues, by all means, optimize!
这篇关于useCallback / useMemo在React中做了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!