cleanup function useeffect code example
Example 1: useeffect with cleanup
useEffect(() => {
return () => {
};
},[]);
Example 2: useEffect
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Example 3: useeffect react
useEffect(() => {
window.addEventListener('mousemove', () => {});
return () => {
window.removeEventListener('mousemove', () => {})
}
}, [])
Example 4: react useeffect
import React, { useEffect } from 'react';
const [data,setData]=useState()
useEffect(() => {
fetch(`put your url/api request in here`)
.then(res=>res.json())
.then(json => setData(json))
},[])
Example 5: clean up useeffect
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
return () => {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
});
Example 6: useeffect cleanup function
function App() {
const [shouldRender, setShouldRender] = useState(true);
useEffect(() => {
setTimeout(() => {
setShouldRender(false);
}, 5000);
}, []);
if( !shouldRender ) return null;
return <ForExample />;
}