effect hook react code example
Example 1: react use effect
useEffect(() => {
},[]);
Example 2: useeffect with cleanup
useEffect(() => {
return () => {
};
},[]);
Example 3: 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 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);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Example 6: use effect react
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
componentDidMount() { document.title = `You clicked ${this.state.count} times`; } componentDidUpdate() { document.title = `You clicked ${this.state.count} times`; }
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}