I'm receiving a React compile warning "The 'fArray' array makes the dependencies of useEffect Hook (at line 79) change on every render. To fix this, wrap the initialization of 'fArray' in its own useMemo() Hook react-hooks/exhaustive-deps".
I've tried using the 'useMemo' for the array, but not sure how to do it correctly in this situation. What is the correct way? ...seems like everything I try produces errors or more warnings.
Here is what I've tried:
//how the array looks prior edits:
let fArray: Stuff[] = [...stuff];
// What I've tried :
const fArray = useMemo(() => { return Stuff[] = [...stuff] }, []);
// BUT, this doesn't work because 'Stuff' only refers to type but is being used as value here
How array is being used:
useEffect(() => {
//other code here....
dispatch(setStuff([fArray[0].id]));
}, [dispatch, fArray]); //eslint-disable-line react-hooks/exhaustive-deps
CodePudding user response:
Stuff
is a type. You are using it as a variable Stuff[] = [...stuff]
You can do,
const fArray = useMemo(() => { return [...stuff] as Stuff[] }, [stuff]);
or you can also do,
interface Stuff {
name: string;
}
const stuff: Stuff[] = [{name: 'x'}, {name: 'y'}] // simulating typescript already knows the type of `stuff`
export default function App() {
const fArray = useMemo(() => { return [...stuff] }, [stuff]);
useEffect(() => {
//other code here....
}, [fArray]);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
Note: Also make sure to add stuff
to the dep array. Otherwise React may not render what you expected to render.