Full-stack Web Technologies

CHAPTER 2
Hooks

Hooks are special functions that React provides that were introduced late in React evolution, but took over very rapidly. The reason is that they allowed writing components more easily and permitted developers to avoid writing classes for each component and just write normal Javascript functions.

Hooks provide "impure" functionality

Hooks are functions provided by react which implement common "impure" functionality so that your React components can be pure functions.

The way this works is the following: whenever a React component is called, the library runtime (the part in control) knows what component is being rendered. Even if we call components in JSX, they are still just a data-structure, so React will always intervene.

Since React is behind the execution of all components, it can intercept certain function calls and react accordingly to your component. The hook functions seem universal, but they behave specially for each component.

Standard React Hooks

useStateProvide a piece of state
useEffectExecute a side effect on a component
useContextMake some data available to a tree of components
useRefStore a piece of state without triggering rendering
useReducerStore a piece of state without triggering rendering
useCallbackAvoid re-creating functions each time
useMemoMemoize a compute-intensive value

Rules of Hooks

Using hooks is easy, but you have to follow two rules:

  1. Call hooks only from React components.

  2. Only call hooks at the top level of a function, and also at the beginning. That is, not inside an if or loop, or an internal function, etc.

The reason for this rules is that React uses the order of the calls to identify each hook. If you call useState twice in a component, distinguishing the two calls is only possible using the call order, and not any other information:

If you wrote:

function WrongComponent() {
  if (Math.random() > 0.5) {
    const [a, setA] = useState(1);
    // ...
  } else {
    const [b, setB] = useState(5);
    // ...
  }
}

since each time you call the WrongComponent only one useState is called,