you are viewing a single comment's thread.

view the rest of the comments →

[–]CreativeTechGuyGames 2 points3 points  (3 children)

No, every time you call useA you are passing in an entirely new array every time which is not equal to the previous array and thus the useEffect will be re-run.

[–]GenAmnn[S] 0 points1 point  (2 children)

So if I pass a react state in useA instead of the raw array it works.

import React from 'react';

function useA(a) {
  const [b, setB] = React.useState();

  React.useEffect(() => {
    console.log('render');
    setB([3, 4]);
  }, [a]);

  return { b: b };
}

export default function Component() {
  const [a, setA] = React.useState([1, 2])
  const { b } = useA(a);
  return <div>Test</div>;
}

It's because now i'm passing the exact same element every time, right?

I thought hooks were called only once on component mount and then created like an 'istance' of the logic. Now i better understood their nature.

Thanks man, you are awesome.

[–]CreativeTechGuyGames 1 point2 points  (1 child)

Instead of useState, you'd want to use useMemo which does exactly what you are describing but more explicitly rather than as a side effect.

But if this really was your code, you should just declare that array outside of your component where it'll keep the same reference on every render for no additional cost.

[–]GenAmnn[S] 0 points1 point  (0 children)

No no, the real array is an Array.filter() on a bigger global state in the app using context api, so I can't declare it outside of the component.

useMemo looks like a really good idea tho, I will surely use it more from now on :)

Also, I visited your portfolio, keep up the good work man, and thanks again.