Reputation: 229
Im pretty new to React and want to grasp the concept of React state and React use effect. Can someone please explain the difference between these two? Preferebly as if you would of explained it to a three year old? :D
Thanks!
Upvotes: 1
Views: 143
Reputation: 24915
State
means knowing about self. As a component, to define a behavior, you need to keep track of few things. These are stored in State
UseEffect
means react to changes in state. This can happen in multiple styles.
UseEffect
can also be supply clean-up function which can be used to clean certain resources.
For example, take a checkbox. On click you need to either check or uncheck it. But how do you know when to do what? This is where state comes into play. You store current behavior and toggle it.
const { useState, useEffect } = React;
const MyCheckBox = (props) => {
const [ checked, setChecked ] = useState(false);
useEffect(() => {
console.log(checked);
}, [ checked ])
return (
<div>
<input type='checkbox' value={ checked } onClick={ () => setChecked(!checked) } /> Test
</div>
)
}
ReactDOM.render(<MyCheckBox />, document.querySelector('.content'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div class='content'></div>
Appropriate usecase:
Assume you need to create an address form. It will have:
Now City is dependent of State and State on Country. So, you can have something like:
selectedCountry
. This is by default empty.selectedCountry
can be passed from countryField
's state as a prop. Here, in useEffect
you can load necessary states and once loaded, you do not need stream so this can be destroyed in cleanupFunction
Upvotes: 1
Reputation: 3119
State is something what defines behavior of a component. i.e.
And useEffect is to react to any change in those State Variables. i.e.
Upvotes: 1