camillalofroth
camillalofroth

Reputation: 229

The difference of React state and React useEffect

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

Answers (2)

Rajesh
Rajesh

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.

  • Handle all changes
  • Handle changes to only this behavior
  • Handle only first time.

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:

  • Country Selector
  • State Selector
  • City Selector
  • Specific address part.

Now City is dependent of State and State on Country. So, you can have something like:

  • Render Country field on page load with state as selectedCountry. This is by default empty.
  • Now on change of this country, you can render state field. Now the 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
  • Same can be done for city field.

Upvotes: 1

Zunaib Imtiaz
Zunaib Imtiaz

Reputation: 3119

State is something what defines behavior of a component. i.e.

  • Show Modal (true/false)

And useEffect is to react to any change in those State Variables. i.e.

  • Modal (Open/Closed) would trigger state change, hence re-render.

Upvotes: 1

Related Questions