Functional React

React is a JavaScript library for building user interfaces.

IMPORTANT

  • This a rough overview of the most recent features of React (v16.13.x)
  • It also includes the most commonly used JavaScript 2015 (or ES6+) features
  • Only functional-related React and JavaScript APIs / features were included

Setup

nvm

See nvm

node, npm, npx

See 2.2. Install node and npm.

NOTE

  • npx is shipped with npm
  • npm is shipped with node

New project

NOTE

  • npx runs the package directly from npm registry without being installed locally
  • . creates the project in current directory

enzyme

NOTE

  • Enzyme is a testing utility built for React to make testing components easier
  • shallow constraints rendering component as a unit
  • See Shallow API methods (e.g. .find, .exists)
  • See Expect API matchers (e.g. toEqual)

start, test, build, eject

NOTE

These run-scripts are included with create-react-app boilerplate.


ES6+

Import

NOTE

The combination of M, { e } is required on react module when using JSX.

Assignment

NOTE

  • let intends to replace the var keyword
  • const (or constant) is an alternative for read-only assignments
  • let and const are block-scoped (unlike the function-scoped var)
  • let and const aren't hoisted and can't be redeclared
  • const can't be re-assigned and assigned reference is immutable
  • The value of the reference passed to const can still be mutable

Function

NOTE

  • The arrow function is a cleaner alternative of the function keyword
  • The curly braces ({}) are required for multiple expressions
  • The open parens (()) are required for zero or multiple arguments
  • return is implicit after the arrow (=>)
  • this is only bound within its own scope
  • There are no bindings for this, arguments and super()
  • There's no prototype
  • It can't be used with constructor

Destructure

NOTE

  • Destructuring also works with arrays (e.g. [x] = [""]).
  • Use : to alias a destructured property (e.g. { k : foo } = o)
  • Destructuring nested objects is also possible (e.g. { lv1 : { lv2 } } = o)

Spread

NOTE

  • [] spreads an array that makes indices as keys (e.g. [...args])
  • {} spreads an object that makes keys as local variables (e.g. {...args})

Object literal

NOTE

Wrap object with () to return an object since the parser sees {} as block scope.

Template literals

NOTE

  • Template literals was previously called as template strings
  • Multi-lined strings are allowed without using + to concatenate

AJAX

fetch

async / await

NOTE

async / await removes the hassle of promise chains (e.g. .then().then().then() ...).

React

Component

Fragment

Verbose

NOTE

A fragment wraps the node tree with an invisible element.

Short syntax

NOTE

The short syntax doesn't require Fragment but don't support keys or attributes.

JSX

Expression

NOTE

  • {} wrapped in quotes will evaluate into a literal string (e.g. "{klass}" as {klass})
  • An expression can evaluate a combination of plain JavaScript and JSX code

Conditionals

If statement

NOTE

The if statement can only be used outside the return statement.

Conditional operator

NOTE

The conditional operator is also known as the ternary operator.

Logical AND

NOTE

  • The logical AND operator is also known as the guard clause
  • It removes the unnecessary use of null as else value

.env.*

NOTE

  • Environment variables must be prefixed with REACT_APP_
  • The web server must be restarted to load environment variables
  • Use process.env to access environment variables from the .env.* file
  • Only NODE_ENV and REACT_APP_ environment variables are read from .env.* file
  • See # misc in .gitignore for other valid environment files

Events

IMPORTANT

  • React event names use camelCase instead of lowercase
  • Event handlers are passed as functions instead of strings
  • .preventDefault must be used instead of return false to remove default behavior
  • Initial value is specified with defaultValue instead of value

onClick

onChange

onSubmit

Props

defaultProps

NOTE

defaultProps sets the default value of the component's props property when empty.

propTypes

NOTE

  • propTypes is a simple built-in type checking feature included with React
  • It ensures that the correct type of data is passed to component's props property
  • See Usage for the list available types

State

IMPORTANT

  • Hooks are introduced in React v16.8 to manage state without using classes
  • They don’t work inside classes and their names are prefixed with use
  • useContext with useReducer can somewhat replace the popular Redux

useState

NOTE

  • useState is a hook for adding state to function-based components
  • It's destructured into two parts, the state variable and state function
  • The variable holds the value and the function is used to update the value
  • The default value of the state can be specified in useState (e.g. useState(0))
  • Using the function without any condition results into an error (Too many re-renders)

useEffect

NOTE

  • useEffect is a hook for peforming side-effects to function-based components
  • Implements class' lifecycle methods: component(Did(Mount|Update)|WillUnmount)
  • It runs on the first render and then after each component update
  • Using it without events results into a warning (Maximum update depth exceeded)
  • The second argument ([count]) runs useEffect only when count's value changed

useReducer

NOTE

It is an alternative for useState aimed towards managing more complex state logic.

useContext

NOTE

  • useContext enables passing data through nested component tree
  • It allows sharing values of the parent down to each child components (a.k.a. global)
  • It's used primarily for data that's used by multiple components at different nested levels
  • The createContext creates the object context
  • The default context value can be specified in useContext (e.g. useContext({}))
  • The context comes with a Provider component to provide the context values
  • The context values are assigned in Provider component's props ' value property
  • These values are accessible with useContext for components within Provider
  • All consumers of Provider will re-render whenever its value changes

Router

NOTE

  • BrowserRouter tracks the URL and preserves the browser history
  • Route renders the component that matches the current URL
  • Switch only renders the first Route that matches the current URL

render

NOTE

render allows inline rendering of components.

component

NOTE

component renders the specified component.

params

NOTE

  • The : prefix captures the dynamic segment of the URL
  • The dynamic part of the URL can be accessed from props.match.params

Link

NOTE

  • Link, unlike a, preserves app state and avoids full-page refresh
  • Components using Link can't be used outside Router

References

Show Comments