react use effect code example
Example 1: useeffect umnount
useEffect(() => {
return () => {
console.log("cleaned up");
};
}, []);
Example 2: react use effect
useEffect(() => {
},[]);
Example 3: 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'));
Example 4: react useEffect
import React, { useEffect } from 'react';
export const App: React.FC = () => {
useEffect(() => {
}, [])
return (
<div>Use Effect!</div>
);
}
Example 5: use effect react
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 6: componentwillunmount hooks
useEffect(() => {
window.addEventListener('mousemove', () => {});
return () => {
window.removeEventListener('mousemove', () => {})
}
}, [])