React StateΒ 

What we’ll cover

  • Recap React props
  • Why we need React state
  • How to use React state on class components
  • Traffic Light: Student Exercise

Recap: What are Props?

  • A way to share data and functionality between components
  • Always passed down from parent to child component
  • Make components configurable and reusable πŸŽ‰πŸŽ‰πŸŽ‰

Using props

function ParentComponent(props) {
  return (
    <section>
      <ChildComponent name="Eric" />
      <ChildComponent name="Mike" />
      <ChildComponent name="Ellen" />
    </section>
Β  );
}

function ChildComponent(props) {
  return <div>Hi {props.name}</div>;
}

Why are props not enough?

The receiving [child] component cannot modify the props it was given


This means we can't ever change the way our applications looks πŸ‘ŽπŸ‘ŽπŸ‘Ž

So how do we make our React apps dynamic?

React State

What is State?

  • Allows a component to update itself and its child components
  • Whenever state changes, the component will re-render
  • Components with state are commonly called "stateful"
  • Components without state are "stateless"

Let's build a stateful component

What to remember about state

  • Define state as a field on the class along with the initial value
Β 
class Counter extends React.Component {
  state = { counter: 0 };
  // ...

  • Update state by calling this.setState()
Β 
this.setState({ counter: newValue });
  • Access state by using this.state.nameOfState
Β 
<p>Current count: {this.state.counter}</p>

Practice time πŸ€“

Can Function Components have State too?

YES! πŸ†

  • Class components define state as an instance field
  • Function components define state using "hooks" - only in React 16.8 or later

Thanks πŸ‘

React State (Sample Lesson for GA)

By Eric Masiello

React State (Sample Lesson for GA)

  • 96