Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React hooks reference values comparison

everyone! Imagine, I have a component SomeComponent. Every time 'b' value changes, useEffect is triggering despite 'b is not in its dependencies

const SomeComponent = () => {
  const a = [1, 2, 3] //just an example of dependency. In real life it will be a changing value
  const b = useSelector(someValueSelector)

  useEffect(() => {
    //do some staff
  }, [a])
}

Is there any way to store reference to 'a' array inside of SomeComponent? The only way I know is to create a wrapper component and pass

a = useMemo(() => [1, 2, 3], [])

as a props to

<SomeComponent a={a} />
like image 710
Aleksandr Avatar asked Dec 01 '25 10:12

Aleksandr


1 Answers

The issue here is that on every re-render a's reference changes and hence the useEffect is triggered again

You can make use of useMemo inside SomeComponent to assign a memoized value to a

const SomeComponent = () => {
  const a = useMemo(() => [1, 2, 3], []); 
  const b = useSelector(someValueSelector)

  useEffect(() => {
    //do some staff
  }, [a])
}
like image 132
Shubham Khatri Avatar answered Dec 04 '25 06:12

Shubham Khatri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!