What’s the Difference Between useState and useEffect?
I Have Seen These Two New Concepts Introduced in React V16. as per My Understanding: useState Is Similar Like setState with Hooks and useEffect Works Similarly...
I have seen these two new concepts introduced in react v16.
As per my understanding:
useStateis similar likesetStatewith hooks anduseEffectworks similarly like life cycle methods.
Is my understanding correct? If not, what’s the exact difference between useState and useEffect?
3 Answers
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:
useStateallows functional components to have state, likethis.statein class components.useEffectallows functional components to have lifecycle methods (such ascomponentDidMount,componentDidUpdateandcomponentWillUnmount) 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=""></script>
<script src=""></script>
<div id="app"></div>