effect java_react useEffect comparing objects

Use apiOptions as state value

I'm not sure how you are consuming the custom hook but making apiOptions a state value by using useState should work just fine. This way you can serve it to your custom hook as a state value like so:

const [apiOptions, setApiOptions] = useState({ a: 1 })

const { data } = useExample(apiOptions)

This way it's going to change only when you use setApiOptions.

Example #1

import { useState, useEffect } from 'react';

const useExample = (apiOptions) => {

const [data, updateData] = useState([]);

useEffect(() => {

console.log('effect triggered')

}, [apiOptions]);

return {

data

};

}

export default function App() {

const [apiOptions, setApiOptions] = useState({ a: 1 })

const { data } = useExample(apiOptions);

const [somethingElse, setSomethingElse] = useState('default state')

return

{ setApiOptions({ a: 1 }) }}>change apiOptions

{ setSomethingElse('state') }}>

change something else to force rerender

;

}

Alternatively

You could write a deep comparable useEffect as described here:

function deepCompareEquals(a, b){

// TODO: implement deep comparison here

// something like lodash

// return _.isEqual(a, b);

}

function useDeepCompareMemoize(value) {

const ref = useRef()

// it can be done by using useMemo as well

// but useRef is rather cleaner and easier

if (!deepCompareEquals(value, ref.current)) {

ref.current = value

}

return ref.current

}

function useDeepCompareEffect(callback, dependencies) {

useEffect(callback, useDeepCompareMemoize(dependencies))

}

You can use it like you'd use useEffect.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值