Please look at the commented code. Why can't I use name as dependency in useMemo?
I want to stop useEffect rerendering the page again just because some referential equality of a variable is changing that's why i used useMemo in themeVar object.
import React, { useState, useEffect, useMemo } from "react";
const External = () => {
const [number, setNumber] = useState(0);
const [dark, setDark] = useState(false);
const doubleNumber = useMemo(() => {
return slowFunction(number);
}, [number]);
const themeStyles = useMemo(() => {
return {
backgroundColor: dark ? "black" : "white",
color: dark ? "white" : "black",
};
}, [dark]);
// const themeVar = useMemo(() => {
// return {
// name : 'parth'
// }
// },[name])
// useEffect(() => {
// console.log('new object')
// },[themeVar])
useEffect(() => {
console.log("theme chnaged");
}, [themeStyles]);
return (
<>
<input
type="number"
value={number}
onChange={(e) => {
setNumber(parseInt(e.target.value));
}}
/>
<button onClick={() => setDark(prevDark => !prevDark)}>Change Theme</button>
<div style={themeStyles}>{doubleNumber}</div>
</>
);
};
function slowFunction(num) {
for (let i = 0; i < 100000000; i++) {}
return num * 2;
}
export default External;
you didn't declared "name" anywhere in your code except themeVar dependency array also you can't use themeVar return object key "name" in dependency array