I wanted to rerun useEffect if the object value changed. And when I searched, I found the solution to use (useMemo) because an object is a reference and a solution like this.
// We want to rerun useEffect if name or age are changed
const [age, setAge] = useState(0);
const [name, setName] = useState('');
const [darkMode, setDarkMode] = useState(false);
/*
We need useMemo because
if person = {age: age, name: name}
this will make useEffect rerun even if darkMode is changed,
and We don't want that so we will use useMemo
*/
const person = useMemo(() => {
return { age: age, name: name };
}, [age, name]);
useEffect(() => {
console.log('useEffect run');
}, [person]);
// or
/*
useEffect(() => {
console.log('useEffect run');
}, [person.age, person.name]);
*/
If I don't know the attribute of person object. How can make useEffect rerun depend on the attribute of person object?
I have two suggestions, and I don't know if they are the best way or not
// suggestion1 (using useMemo like that)
const personValues = Object.keys(person).map((att) => person[att]);
const personMemo = useMemo(() => {
return { ...person};
}, [...personValues ]);
useEffect(() => {
console.log('useEffect run');
}, [personMemo]);
// suggestion2 (don't use useMemo)
const personValues = Object.keys(person).map((att) => person[att]);
useEffect(() => {
console.log('useEffect run');
}, [...personValues]);
I tried to spread the attribute of the person object inside useEffect's dependency array, I think this is a good way for that and I want to know if there is a better way or not