8bitzz / blogs

0 stars 0 forks source link

ReactJS Props vs. State #2

Open 8bitzz opened 3 years ago

8bitzz commented 3 years ago

Common ground

Stateless Component

Stateful Component

Props

Props are passed into the components

const element = ;

could be written as
```jsx
function Welcome(props) {
  return <h1>Hello {props.name}</h1>;
}

Welcome.defaultProps = { name: "world", };

If `Welcome` is called without a `name` it will simply render `<h1> Hello world</h1>`
#### Props should not change
- Props contains information set by the parent component (although defaults can be set) and should not be changed
- React components that use only `props` are considered as `pure`, they render the same output given the same input (props that passed in)

### State

#### State is created in the component
```jsx
class Button extends React.Component {
  constructor() {
    super();
    this.state = {
      count: 0,
    };
  }

  updateCount() {
    this.setState((prevState, props) => {
      return { count: prevState.count + 1 }
    });
  }

  render() {
    return (<button
              onClick={() => this.updateCount()}
            >
              Clicked {this.state.count} times
            </button>);
  }
}

The constructor is where state gets its initial data. The inital data can be hard coded as above (count: 0), but it can also come from props.

State is changeable

Do not use

// DO NOT USE
this.state.count = this.state.count + 1

React cannot listen to the state getting updated in this way, so your component will not re-render

Do not use

// DO NOT USE
this.setState({
  count: this.state.count + 1
});

This does not take into account the asychronous nature that setState can use and might cause errors.

Do use

// DO USE
render() {
  return (<button
            onClick={() => this.updateCount()}
          >
            Clicked {this.state.count} times
          </button>);
}

The State flow