Issue
I have seen these two new concepts introduced in react v16.
As per my understanding:
useState
is similar likesetState
with hooks anduseEffect
works similarly like life cycle methods.
Is my understanding correct? If not, what’s the exact difference between useState
and useEffect
?
Solution
To put it simply, both useState
and useEffect
enhance functional components to make them do things that classes can but functional components (without hooks) cannot:
useState
allows functional components to have state, likethis.state
in class components.useEffect
allows functional components to have lifecycle methods (such ascomponentDidMount
,componentDidUpdate
andcomponentWillUnmount
) in one single API.
Refer to the examples below for further illustration:
useState
class CounterClass extends React.Component {
constructor(props) {
super(props);
this.state = { count: 1 };
}
render() {
return <div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.setState({
count: this.state.count + 1
})}>Increase</button>
</div>;
}
}
function CounterFunction() {
const [count, setCount] = React.useState(1);
return (
<div>
<p>Count: {count}</p>
<button onClick={() =>
setCount(count + 1)}
>Increase</button>
</div>
);
}
ReactDOM.render(
<div>
<CounterClass />
<CounterFunction />
</div>
, document.querySelector('#app'));
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
<div id="app"></div>
useEffect
class LifecycleClass extends React.Component {
componentDidMount() {
console.log('Mounted');
}
componentWillUnmount() {
console.log('Will unmount');
}
render() {
return <div>Lifecycle Class</div>;
}
}
function LifecycleFunction() {
React.useEffect(() => {
console.log('Mounted');
return () => {
console.log('Will unmount');
};
}, []); // Empty array means to only run once on mount.
return (
<div>Lifecycle Function</div>
);
}
ReactDOM.render(
<div>
<LifecycleClass />
<LifecycleFunction />
</div>
, document.querySelector('#app'));
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
<div id="app"></div>
Read more about useState and useEffect on the official React docs.
Answered By - Yangshun Tay
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.