Skip to content

Props and State

Billy Bunn edited this page Apr 25, 2019 · 1 revision

setState()

You can't/shouldn't ever touch state directly; setState() is a React component method that is used to properly change state.

Editing state directly might seem to work if you're just looking at the state, but it doesn't do any of the important work behind-the-scenes that setState() does.

CSS Tricks puts it best:

The reconciliation process is the way React updates the DOM, by making changes to the component based on the change in state. When the request to setState() is triggered, React creates a new tree containing the reactive elements in the component (along with the updated state). This tree is used to figure out how the ... component’s UI should change in response to the state change by comparing it with the elements of the previous tree. React knows which changes to implement and will only update the parts of the DOM where necessary. This is why React is fast.

Functional vs Class Components

React components can be created in two primary ways: as functions or as classes.

Functional React components get the React component props by passing them in as a parameter. Class components get props through a constructor function.

When would you choose to use one over the other? This mainly has to do with state. Because a functional component is just a plain JavaScript function, you cannot use setState(). So if you need to use state in your component, you either need to make it a class with its own state or pass down state through props from the parent component.

Note: React has a recent update (16.8) which adds hooks—a way to access state in a functional component. Read more here.

Handling Events

Forms

Clone this wiki locally