Hooks

Published Jul 29, 2021Updated Oct 31, 2022
Contribute to Docs

In React, hooks are functions that give class-like abilities to function components, including state and side-effects.

There are a few rules when using hooks, including the following:

  • Hooks must be called from React functions (i.e. components or custom hooks) and not from a regular JavaScript function.
  • Hooks should not be called inside of a loop, condition, or nested function. Instead, hooks should be called at the top level of a React function so they render in the same order every time.

While there are standard React hooks, like useState() and useEffect(), there are also custom-made hooks!

Syntax

import React, { useHook } from 'react';

Hooks are imported at the top of a file from the react library:

Note: The code snippet above is purely pseudocode and useHook is not an actual React hook.

Hooks

useContext()
Subscribes a component to a context which includes its value prop that exists further up the component tree.
useEffect()
Takes in a function and an array. The function will be executed after the current render phase finishes and only if the elements inside the array has changed from the previous render.
useRef()
Creates mutable references to elements or values, allowing access to them without causing re-renders.
useState()
Returns the current state of the component and its setter function

All contributors

Looking to contribute?

Learn React on Codecademy