useEffect reactjs code example
Example 1: useeffect with cleanup
useEffect(() => {
return () => {
};
},[]);
Example 2: useeffect
function App() {
const [count, setCount] = useState(0);
useEffect(() => {
longResolve().then(() => {
alert(count);
});
}, []);
return (
<div>
<button
onClick={() => {
setCount(count + 1);
}}
>
Count: {count}
</button>
</div>
);
}
Example 3: useeffect react
useEffect(() => {
return () => {
};
},[]);
Example 4: 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 5: useeffect react
useEffect(() => {
window.addEventListener('mousemove', () => {});
return () => {
window.removeEventListener('mousemove', () => {})
}
}, [])
Example 6: react useEffect
import React, { useEffect, useState } from 'react';
import ReactDOM from 'react-dom';
function LifecycleDemo() {
useEffect(() => {
console.log('render!');
return () => console.log('unmounting...');
}, [
return "I'm a lifecycle demo";
}
function App() {
const [random, setRandom] = useState(Math.random());
const [mounted, setMounted] = useState(true);
const reRender = () => setRandom(Math.random());
const toggle = () => setMounted(!mounted);
return (
<>
<button onClick={reRender}>Re-render</button>
<button onClick={toggle}>Show/Hide LifecycleDemo</button>
{mounted && <LifecycleDemo/>}
</>
);
}
ReactDOM.render(<App/>, document.querySelector('#root'));