React basics - jellyfish-tom/TIL GitHub Wiki

[SOURCES]

Elements

Elements are the smallest building blocks of React apps.

An element describes what you want to see on the screen:

const element = <h1>Hello, world</h1>;

One might confuse elements with a more widely known concept of “components”. Components are “made of” elements.

React elements are immutable. Once you create an element, you can’t change its children or attributes. An element is like a single frame in a movie: it represents the UI at a certain point in time.

React DOM compares the element and its children to the previous one, and only applies the DOM updates necessary to bring the DOM to the desired state.

Components

Components let you split the UI into independent, reusable pieces, and think about each piece in isolation. This page provides an introduction to the idea of components.

Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen

The simplest way to define a component is to write a JavaScript function:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

You can also use an ES6 class to define a component:

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

*** Props of component are Read-Only ***

Whether you declare a component as a function or a class, it must never modify its own props. Consider this sum function:

function sum(a, b) {
  return a + b;
}

Such functions are called “pure” because they do not attempt to change their inputs, and always return the same result for the same inputs.

In contrast, this function is impure because it changes its own input:

function withdraw(account, amount) {
  account.total -= amount;
}

React is pretty flexible but it has a single strict rule:

All React components must act like pure functions with respect to their props.

Of course, application UIs are dynamic and change over time but one simply do not use props to achieve that. State allows React components to change their output over time in response to user actions, network responses, and anything else, without violating this rule.

Converting a Function to a Class

function Clock(props) {
  return (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {props.date.toLocaleTimeString()}.</h2>
    </div>
  );
}

You can convert a function component like Clock to a class in five steps:

  • Create an ES6 class, with the same name, that extends React.Component.
  • Add a single empty method to it called render().
  • Move the body of the function into the render() method.
  • Replace props with this.props in the render() body.
  • Delete the remaining empty function declaration.
class Clock extends React.Component {
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.props.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

State

State Updates May Be Asynchronous

React may batch multiple setState() calls into a single update for performance.

Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

For example, this code may fail to update the counter:

// Wrong
this.setState({
  counter: this.state.counter + this.props.increment,
});

To fix it, use a second form of setState() that accepts a function rather than an object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument:

// Correct
this.setState((state, props) => ({
  counter: state.counter + props.increment
}));

Composition vs inheritance

Generally whole this page is interesting, so am not copying, just read it:

https://reactjs.org/docs/composition-vs-inheritance.html

Second Take

What is React Component

Component is a small, isolated piece of code that is composable with other such pieces of code that together create UI. React is a library that allows developer to create and display such components.

What is React Element

React element is what render() method returns. That is description of what will be visible on the screen. render() method basically returns React.createElement() that wraps other React.createElement() methods.

What is JSX

JSX is robust syntax used to efficiently write React components, without need to repeatedly call React methods to create elements. JSX is just an abbreviation. Syntax sugar.

Why Immutability is important

  • Check this https://immerjs.github.io/immer/docs/introduction

  • Complex Features Become Simple Immutability makes complex features much easier to implement.Avoiding direct data mutation lets us keep previous versions of the game’s history intact, and reuse them later.

  • Detecting Changes Detecting changes in mutable objects is difficult because they are modified directly. This detection requires the mutable object to be compared to previous copies of itself and the entire object tree to be traversed. Detecting changes in immutable objects is considerably easier. If the immutable object that is being referenced is different than the previous one, then the object has changed.

  • Determining When to Re-Render in React The main benefit of immutability is that it helps you build pure components in React. Immutable data can easily determine if changes have been made which helps to determine when a component requires re-rendering.

Keys

When a list is re-rendered, React takes each list item’s key and searches the previous list’s items for a matching key. If the current list has a key that didn’t exist before, React creates a component. If the current list is missing a key that existed in the previous list, React destroys the previous component. If two keys match, the corresponding component is moved. Keys tell React about the identity of each component which allows React to maintain state between re-renders. If a component’s key changes, the component will be destroyed and re-created with a new state.

Keys do not need to be globally unique; they only need to be unique between components and their siblings.

⚠️ **GitHub.com Fallback** ⚠️