Post/Code

HomeAboutUsesNow

React Tutorial Notes.

These are some notes I made while working through the official React Tutorial.

  • React components (except for function components) define super(props) in the constructor (when used)
  • Components (except for function components) extend React.Component and have a render function which returns the component.
  • Class components display information via this.props. Function components do not make use of this.
  • React is only a view.
  • When you call setState in a component, React automatically updates the child components.

Lifting State

"...the best approach is to store the game's state in the parent Board component instead of in each Square. The Board component can tell each Square what to display by passing a prop..." - Lifing state

  • Declare the shared state in the parent component. Parent component can pass the state back down to the children by using props. This keeps the children in sync with each other and with the parent component.

  • Lifting state into a parent component is common in React when refactoring.

"In React, however, it is a convention to use on [Event] names for props which represent events and handle [Event] for the methods which handle the events." - Lifting state

  • Child components should not store state and the inform parents of events which are bubbled up. These are ‘dumb’ or rather ‘controlled components’.

Benefits of immutability

  • Complex features become simple - for example, time-travel. Avoiding direct data mutation lets us keep previous versions of history intact and can be re-used later.

  • Detecting changes - detecting change in mutable object is difficult as they are modified directly. This detection requires mutable object to be compared to previous copies of itself and the entire object tree to be traversed. Detecting changes in immutable object is easier since if the object being reference is different than the previous one, the object has changed.

  • Re-rendering - the primary benefit is that you can build pure components. Easily determine change and then determine if re-render is required.

  • Function components only contain one render function - as such, can re-write it to only be a function that takes props as an argument and is not a class. In a class, you need a proper arrow function to access this. In function component, you do not need to access this, so you do not need the arrow function to access the props.

Key

  • Strongly recommended to assign proper keys when building dynamic lists!

"key is a special and reserved property in React (along with ref, a more advanced feature). When an element is created, React extracts the key property and stores the key directly on the returned element. Even though key may look like it belongs in props, key cannot be referenced using this.props.key. React automatically uses key to decide which components to update. A component cannot inquire about its key." - Picking a key