React Cheatsheet

Table of Contents

React.js is a declarative, component based JavaScript library for building user interfaces.

Stateful Class Component

import React from 'react'

class Counter extends React.Component {
    state = {
        count: this.props.initialCount
    }
    inc = () => {
        this.setState({
            count: this.state.count + 1
        })
    }
    dec = () => {
        this.setState({
            count: this.state.count > 0 ? this.state.count - 1 : 0
        })
    }
    reset = () => {
        this.setState({
            count: 0
        })
    }
    render() {
        return (
            <div>
                <span className="count">The count is: {this.state.count}</span>
                <button onClick={this.inc}>+</button>
                <button onClick={this.dec}>-</button>
                <button onClick={this.reset}>0</button>
            </div>
        )
    }
}

export default Counter

Stateless Function Component

import React from 'react'

function Hello({ firstName, lastName }) {
    return (
        <p className="greeting">
            Hello {firstName} {lastName}
        </p>
    )
}

export default Hello

Stateful Function Component

import React from 'react'

function Counter({ initialCount }) {
    const [count, setCount] = React.useState(initialCount)

    const inc = () => setCount(c => c + 1)
    const dec = () => setCount(c => (c > 0 ? c - 1 : 0))
    const reset = () => setCount(0)

    return (
        <div>
            <span className="count">The count is: {count}</span>
            <button onClick={inc}>+</button>
            <button onClick={dec}>-</button>
            <button onClick={reset}>0</button>
        </div>
    )
}

export default Counter

React Hooks

Summary of Hooks

HookDescription
useStatePersists a value between renders. Updates will trigger a render.
useEffectHandles side-effects such as getting data from a server or communicating with the browser API.
useContextReturns the current context value for the specified context object.
useRefPersist a value between renders, does not trigger a render.
useImperativeHandleCustomize the instance value that is exposed to parent components when using ref.
useReducerPersists a value between renders. Manages the state via the reducer pattern. Updates will trigger a render.
useMemoMemoize a value between renders.
useCallbackMemoize a function between renders.

useState

Persists a value between renders. Updates will trigger a render.

const [state, setState] = React.useState(initialStateValue)

useEffect

Handle side-effects such as getting data from a server or communicating with the browser API (such as history, local storage, or geolocation services).

React.useEffect(() => {
  /* side-effect code goes here */
  /* optionally return a cleanup function */
  },
  /* optional array of triggers:
        - `undefined` (if not provided): runs the effect after every render
        - `[]`: an empty array, runs the effect after the component is mounted (componentDidMount)
        - `[a, b, c]`: a non-empty array, runs the effect when any of these state or property values mutates (i.e. refers to a new memory location)
  */
}

useContext

Returns the current context value for the specified context object.

import ThemeContext from './ThemeContext'
...
const context = React.useContext(ThemeContext)

useRef

Persist a value between renders, does not trigger a render.

import React from 'react'

function TextInputWithFocusButton() {
    const inputRef = React.useRef(null) // initialize inputRef.current to null
    const onButtonClick = () => {
        inputRef.current.focus() // inputRef.current points to the DOM node
    }
    return (
        <>
            <input ref={inputRef} type="text" />{' '}
            {/* React sets inputRef.current to the input DOM element */}
            <button onClick={onButtonClick}>Focus the input</button>
        </>
    )
}

export default TextInputWithFocusButton

useImperativeHandle

Customize the instance value that is exposed to parent components when using ref.

NOTE: useImperativeHandle should be used with forwardRef.

useRef vs. useImperativeHandle

useImperativeHandle provides a way to customize the object that is exposed to parent components that use a ref. For example, the customized object could have additional methods that the parent component can call so that it can directly interact with the ref.

useReducer

Persists a value between renders. Manages the state via the reducer pattern. Updates will trigger a render.

import React from 'react'

function reducer(state, action) {
    switch (action.type) {
        case 'increment':
            return { count: state.count + 1 }
        case 'decrement':
            return { count: state.count > 0 ? state.count - 1 : 0 }
        case 'reset':
            return { count: 0 }
        default:
            throw new Error()
    }
}

function Counter({ initialCount }) {
    const initialState = { count: initialCount }
    const [state, dispatch] = React.useReducer(reducer, initialState)
    return (
        <div>
            <span className="count">The count is: {state.count}</span>
            <button onClick={() => dispatch({ type: 'increment' })}>+</button>
            <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
            <button onClick={() => dispatch({ type: 'reset' })}>0</button>
        </div>
    )
}

export default Counter

useMemo

Memoize a value between renders.

const memoizedValue = useMemo(() => {
    computeExpensiveValue(a, b)
}, [a, b])

useCallback

Memoize a function between renders.

const memoizedCallback = useCallback(() => {
    doSomething(a, b)
}, [a, b])

useMemo vs. useCallback

Both useMemo and useCallback take functions as arguments. The difference is that useCallback returns its function when the dependencies change while useMemo calls its function and returns the result.

In other words:

hookdescription
useCallbackgives you referential equality between renders for functions
useMemogives you referential equality between renders for values
Dr. Mike Hopper avatar
Dr. Mike Hopper
Software Architect, Engineer, and Instructor