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

3

14

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]);
Floppy answered 14/10, 2021 at 14:37 Comment(2)
Please , can you share your code with snack.expo.dev , it will be easier to help you with all yours codeTrish
@Trish sorry but can't do thisFloppy
Z
31
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 :)

Zimmermann answered 14/10, 2021 at 14:55 Comment(2)
I have replaced this with "let slider1 = []" but now the warnings are warning: 'useMemo' is not defined & warning: 'slider1' is constantFloppy
@ALiRazaDarr: you must import the hook first: import React, { useState, useEffect, useMemo } from 'react';Lengel
R
1

Don't forget to import the hook

import React, { useState, useEffect, useMemo } from 'react';

Rumania answered 23/11, 2021 at 14:30 Comment(0)
J
0

I had the same issue but with an array that had values so I figured I would post what did after I imported the hook.

import { useMemo } from 'react';

const events = useMemo(() => { return ['load', 'mousemove', 'click', 'scroll', 'keypress']; }, []);

hope this helps someone.

Jessi answered 24/8, 2023 at 21:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.