Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
118
rated 0 times [  122] [ 4]  / answers: 1 / hits: 58227  / 5 Years ago, sat, july 13, 2019, 12:00:00

I've been learning React and I read that the function returned from useEffect is meant to do cleanup and React performs the cleanup when the component unmounts.



So I experimented with it a bit but found in the following example that the function was called every time the component re-renders as opposed to only the time it got unmounted from the DOM, i.e. it console.log(unmount); every time the component re-renders.



Why is that?



function Something({ setShow }) {
const [array, setArray] = useState([]);
const myRef = useRef(null);

useEffect(() => {
const id = setInterval(() => {
setArray(array.concat(hello));
}, 3000);
myRef.current = id;
return () => {
console.log(unmount);
clearInterval(myRef.current);
};
}, [array]);

const unmount = () => {
setShow(false);
};

return (
<div>
{array.map((item, index) => {
return (
<p key={index}>
{Array(index + 1)
.fill(item)
.join()}
</p>
);
})}
<button onClick={() => unmount()}>close</button>
</div>
);
}

function App() {
const [show, setShow] = useState(true);

return show ? <Something setShow={setShow} /> : null;
}


Live example: https://codesandbox.io/s/vigilant-leavitt-z1jd2


More From » reactjs

 Answers
15

React performs the cleanup when the component unmounts.




I'm not sure where you read this but this statement is incorrect. React performs the cleanup when the dependencies to that hook changes and the effect hook needs to run again with new values. This behaviour is intentional to maintain the reactivity of the view to changing data. Going off the official example, let's say an app subscribes to status updates from a friends' profile. Being the great friend you are, you are decide to unfriend them and befriend someone else. Now the app needs to unsubscribe from the previous friend's status updates and listen to updates from your new friend. This is natural and easy to achieve with the way useEffect works.



 useEffect(() => { 
chatAPI.subscribe(props.friend.id);

return () => chatAPI.unsubscribe(props.friend.id);
}, [ props.friend.id ])


By including the friend id in the dependency list, we can indicate that the hook needs to run only when the friend id changes.



In your example you have specified the array in the dependency list and you are changing the array at a set interval. Every time you change the array, the hook reruns.



You can achieve the correct functionality simply by removing the array from the dependency list and using the callback version of the setState hook. The callback version always operates on the previous version of the state, so there is no need to refresh the hook every time the array changes.



  useEffect(() => {
const id = setInterval(() => setArray(array => [ ...array, hello ]), 3000);

return () => {
console.log(unmount);
clearInterval(id);
};
}, []);


Some additional feedback would be to use the id directly in clearInterval as the value is closed upon (captured) when you create the cleanup function. There is no need to save it to a ref.


[#51885] Monday, July 8, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jessie

Total Points: 713
Total Questions: 87
Total Answers: 109

Location: Australia
Member since Sat, May 27, 2023
1 Year ago
;