Skip to main content

React Hooks

React hooks are the only way to tie your app into the React framework.

hooks are just another functions.

Hooks are just plain functions. They run each time the component renders.

ReactJS hooks and JavaScript closures

All React hooks use closures inside. React makes a closure during each render with the current values. It uses this to compare new values, store current ones, and re-render when needed.

react-hooks-closure

useCallback

This hook caches the object Id of the function. This matters because a child function gets a new reference each time the parent runs.

How React uses child functions

In React, every component is just a JavaScript function. All functions inside it are child functions. Each re-render makes a new reference for a child function.

A re-render builds those functions again. If you pass one down as a prop, it makes the child components re-render with no need. This is where useCallback helps.

useCallback implementation

When a component re-renders, useCallback runs. It compares the old function body with the new one. It also compares the dependencies.

useMemo

This is like useCallback. But it caches the return value, not the function reference. It helps when a function is costly to run and you want to skip needless runs.

useEffect

This is again a plain method. It runs each time the component renders.

useEffect runs the function in its first argument, but only if the dependency values changed. React stores the old dependency values in its internal storage.

useState

  1. On each new render, useState() returns the current value and a new closure setter method.
  2. The setter method also calls the function that queues a re-render with the new state. It runs whenever an event fires this setter.