Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap the initialisation of an array in its own useMemo() Hook?

Can someone please give the solution to this warning message?

137:7 warning The 'slider1' array makes the dependencies of useEffect Hook (at line 143) change on every render. To fix this, wrap the initialization of 'slider1' in its own useMemo() Hook react-hooks/exhaustive-deps

138:7 warning The 'slider2' array makes the dependencies of useEffect Hook (at line 143) change on every render. To fix this, wrap the initialization of 'slider2' in its own useMemo() Hook react-hooks/exhaustive-deps

I am new to react and have no experience with it. It would be nice if someone can provide the complete solution.

Here is the code:

  const [nav1, setNav1] = useState(null);
  const [nav2, setNav2] = useState(null);
  let slider1 = [];
  let slider2 = [];

  useEffect(() => {
  setNav1(slider1);
  setNav2(slider2);
  }, [slider1, slider2]);
like image 401
ALi Raza Darr Avatar asked Feb 02 '26 16:02

ALi Raza Darr


1 Answers

const slider1 = useMemo(() => [], []);

As simple as that :)

Also know the problem here, let variable in React recreates itself on every tick, since every tick will rerun useEffect you'd have an infinite loop going on :) You could also use it as state default value instead of null :)

like image 67
majkelS Avatar answered Feb 05 '26 07:02

majkelS



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!