[React] useCallback + useMemo to avoid re-render

With React hooks it's common to write callback functions in our component body. Event handlers are a common example of this. Most of the time they work great, however, when you're passing those event handlers down to a child component or using them as dependencies in another hook such as useEffect they can be a little bit tricky. Because the functions are re-created on every single render, the reference to that function changes. And each time it changes when it's used as a prop or a dependency, it will force an update. The useCallback hook was created to provide stable references to callback functions to avoid this problem. It's not always needed, but this lesson will show you how to use it when it's needed.

In this lesson we start off by completing the conversion of our <AmountField> to using the Redux Hooks API, but in doing so introduce a new problem: our debouncing stops working. It turns out that by defining our dispatched action inline our useMemo hook was relying on an unstable function reference. Each time we changed the AmountField, we ended up creating a new debounced function and immediately firing off the call to update our rate table. To solve this problem we wrap our dispatched action function in useCallback.

It's important to note that useCallback is not needed for every callback function you create and should only be used when there are real performance issues at hand.

 

// changeAmount function is re-created every time the component re-render
const changeAmount = (newAmount) => dispatch(amountChanged(newAmount));

// that cause the problem for onAmountChanged function do extra re-rendering
const onAmountChanged = useMemo(() => debounce(changeAmount, 500), [changeAmount])

 

We can use `useCallback` to solve the problem:

const changeAmount = useCallback(
    (newAmount) => dispatch(amountChanged(newAmount)),
    []
);

Now, each time the component re-render, it won't change `changeAmount` variable.

 

posted @   Zhentiw  阅读(91)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-09-10 [CSS] Use CSS pseudo-elements and mix-blend-mode to Create a Duotone Style Effect
2020-09-10 [Machine Learning] Backpropagation Algorithm
2020-09-10 [Machine Learning] Neural Network: Cost Function
2015-09-10 [React] Intro to inline styles in React components
2015-09-10 [AngualrJS + Webpack] Production Source Maps
2015-09-10 [AngularJS + Webpack] Uglifying your JavaScript
点击右上角即可分享
微信分享提示