Back to roadmaps react Course

React Hooks Cheat Sheet

This quick reference guide provides code snippets for the most common hooks in React.


1. useState

import { useState } from "react";

// Declaration
const [value, setValue] = useState(0);

// Simple Update
setValue(10);

// Functional Update (depends on previous state value)
setValue(prev => prev + 1);

2. useEffect

import { useEffect } from "react";

useEffect(() => {
  // Side effect setup logic
  console.log("Component updated");

  // Optional cleanup function
  return () => {
    console.log("Cleanup performed");
  };
}, [dependency1]); // Dependency array governs execution frequency

3. useContext

import { createContext, useContext } from "react";

const ThemeContext = createContext("light");

// Consuming context value in a child component
const theme = useContext(ThemeContext);

4. useRef

import { useRef, useEffect } from "react";

// 1. Persisting mutable values (does not trigger re-renders)
const count = useRef(0);
count.current += 1;

// 2. Accessing DOM nodes
const inputEl = useRef(null);
useEffect(() => {
  inputEl.current.focus();
}, []);

// Render element
// <input ref={inputEl} />

5. useReducer

import { useReducer } from "react";

const initialState = { count: 0 };

function reducer(state, action) {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
    default:
      throw new Error();
  }
}

// Instantiate reducer hook
const [state, dispatch] = useReducer(reducer, initialState);

// Trigger action
// dispatch({ type: "increment" });
Published on Last updated: