Hooks

Hooks let “function components” use React features like state, lifecycle, context, and refs. Previously that required “class components”.

Hooks make components simpler because:

  • Just write a function. No class constructors or binding needed.
  • Stateful logic can be reused across components.
  • Related logic is grouped in a single effect (not spread across lifecycle events).
  • Avoid confusing patterns like render-props and higher-order-components that lead to “wrapper hell”.

The simplest example

This code updates a counter with the built-in useState and useEffect hooks.

import React, { useEffect, useState } from 'react';

function Example() {
    // Declare a new state variable, which we'll call "count"
    const [count, setCount] = useState(0);

    // Similar to componentDidMount and componentDidUpdate:
    useEffect(() => {
        // Update the document title using the browser API
        document.title = `You clicked ${count} times`;
    });

    return (
        <div>
            <p>You clicked {count} times</p>

            <button onClick={() => setCount(count + 1)}>
                Click me
            </button>
        </div>
    );
}

Learn

⭐️ ReactJS — Introducing hooks
The best way to learn hooks (2 hours). Comprehensive and well-written docs from the React team.

  • Why hooks needed to exist.
  • What hooks do.
  • Using useState and useEffect hooks to refactor classes.
  • Building custom hooks.
  • FAQ + edge cases.

⭐️ ReactJS — Hooks API reference
See the full API + docs.

Tutorials

CSS Tricks — Intro to React hooks
Isolated examples of useState, useEffect, and useContext hooks.

Tania Rascia — Build a CRUD app in React with hooks
Good continuous intro + tutorial to useState and useEffect hooks.

Hackernoon — Learn React Hooks by building an auth-based to-do app
A longer tutorial that also incorporates useRef and useReducer hooks.

Courses

Scott Tolinski — React hooks for everyone
$40 for 22 videos (2.5 hours).

I didn’t buy this course, but some of the advanced use cases look interesting.

Advanced articles

Amelia Wattenberger — Thinking in React Hooks
Minimal intro — but beautifully visualized examples of why you should refactor classes as hooks.

Scotch — 5 ways to convert React class components to functional components with React hooks
Before/after examples of refactoring componentDidMount and componentDidUpdate with hooks.

⭐️ Dan Abramov — Making setInterval declarative with React hooks

This is what gets me excited about Hooks and React all over again. We can wrap the existing imperative APIs and create declarative APIs expressing our intent more closely. Just like with rendering, we can describe the process at all points in time simultaneously instead of carefully issuing commands to manipulate it.

⭐️ Dan Abramov — A complete guide to useEffect
Deep dive into useEffect behaviors and edge cases.

  • State values don’t change between renders. The entire function (and its constants + sub-functions) is different on every render.
  • React synchronizes the DOM according to our current props and state. There is no distinction between a “mount” or an “update” when rendering. useEffect lets you synchronize things outside of the React tree according to our props and state.
  • Effect dependencies let you explicitly tell React if a value used in the effect may change. If provided it can diff the value and determine whether to run the effect’s function or not. Otherwise, React always runs the effect.
  • Passing [] for dependencies is equivalent to “all dependencies are always equal”, which is usually not the same intent as “only run the effect once”.
  • If you define effect dependencies, always define everything used in the function to avoid bugs.
  • To avoid dependencies altogether, consider using the “functional updater” form for setState like: setCount(c => c + 1) which doesn’t read any values from the render scope.
  • Or use a reducer instead.
  • Put functions only used inside an effect directly into that effect’s function body. Then it’s not a dependency from the outer scope.

Recipes

Recipes for common uses of Hooks.

Dan Abramov — Fetch data with useEffect
Query an API with the useEffect hook.

⭐️ Robin Wieruch — How to fetch data with React Hooks
Query an API with the useEffect hook, then create a reusable useDataApi custom hook.

  • Attach form events and loading/error states.
  • Extract logic into a custom hook with a reducer and handle aborted requests.

Use Hooks
List of custom hooks to reuse in any application.

  • useAnimation
  • useAuth
  • useEventListener
  • useDarkMode
  • useDebounce
  • useHistory
  • useHover
  • useKeyPress
  • useLocalStorage
  • useLockBodyScroll
  • useMedia (media query)
  • useMemo
  • useOnClickOutside
  • useOnScreen
  • usePrevious
  • useScript
  • useSpring (animation library)
  • useTheme
  • useWhyDidYouUpdate
  • useWindowSize

Amelia Wattenberger — Thinking in React Hooks Scroll to the bottom. List of custom hooks to reuse in any application.

  • useChartDimensions
  • useCookie
  • useHash
  • useInterval
  • useIsInView
  • useIsMounted
  • useLocalStorage
  • useOnKeyPress