react usememo_如何使用useMemo React钩子

react usememo

Check out my React hooks introduction first, if you’re new to them.

如果您是新手,请先查看我的React hooks简介

One React hook I sometimes use is useMemo.

我有时使用的一个React挂钩是useMemo

import React, { useMemo } from 'react'

This hook is used to create a memoized value.

该钩子用于创建一个记忆值。

This hook is very similar to useCallback, the difference is that useCallback returns a memoized callback and useMemo returns a memoized value, the result of that function call. The use case is different, too. useCallback is used for callbacks passed to child components.

该钩子与useCallback非常相似,不同之处在于useCallback返回一个已记忆的回调,而useMemo返回一个已记忆的值,即该函数调用的结果。 用例也不同。 useCallback用于传递给子组件的回调。

Sometimes you have to compute a value, either through a complex calculation or by reaching to the database to make a costly query or to the network.

有时,您必须通过复杂的计算或通过访问数据库以进行昂贵的查询或通过网络来计算值。

Using this hook, this operation is done only once, then the value will be stored in the memoized value and the next time you want to reference it, you’ll get it much faster.

使用此钩子,此操作仅执行一次,然后该值将存储在已存储的值中,并且下次您要引用它时,它将更快地得到它。

Here’s how to use it:

使用方法如下:

const memoizedValue = useMemo(() => expensiveOperation())

Make sure you add that empty array as a second parameter to useMemo(), otherwise no memoization will happen at all.

确保将该空数组添加为useMemo()的第二个参数,否则根本不会发生任何useMemo()

If you need to pass arguments, you also need to pass them in the array:

如果需要传递参数,则还需要在数组中传递参数:

const memoizedValue = useMemo(() => expensiveOperation(param1, param2), [param1, param2])

If one of the parameters change when you try to access the value, the value of course will be calculated without memoization.

如果您尝试访问该值时其中一个参数发生更改,则当然会在没有备注的情况下计算该值。

翻译自: https://flaviocopes.com/react-hook-usememo/

react usememo

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值