Blog/NotesConcept

Core React Hooks Cheat Sheet - Explain All React Hooks with Examples

Quick cheat sheet to revise all 13 Core React Hooks with explanations and code examples. Comprehensive guide for Core React Hooks.

Intermediate

Anuj Sharma

Last Updated Jun 27, 2026


Core React Hooks Cheat Sheet - Explain All React Hooks with Examples

Mastering the 13 Core React Hooks is essential for every frontend developer preparing for React interviews. These hooks form the foundation of modern React development and are frequently asked in frontend interviews at startups as well as top product-based companies.

This guide serves as a quick cheat sheet to help you revise all 13 core React Hooks with concise explanations, practical code examples, and common use cases. 

Let's dive into the 13 Core React Hooks every frontend developer should know.

Jump Directly to the Core Hook
  1. useState Hook
  2. useEffect Hook
  3. useRef Hook
  4. useContext Hook
  5. useReducer Hook
  6. useMemo Hook
  7. useCallback Hook
  8. useLayoutEffect Hook
  9. useId Hook
  10. useTransition Hook
  11. useDeferredValue Hook
  12. useImperativeHandle Hook
  13. useSyncExternalStore Hook

1. useState Hook

useState is a Hook that allows functional components in React to have state variables. It provides a way to add state to functional components without having to convert them to class components.

Syntax

const [state, setState] = useState(initialState);
  • state: The current state value.
  • setState: Function that allows you to update the state.
  • initialState: The initial value of the state.

Code Implementation

import React, { useState } from 'react';

const Counter = () => {
  const [count, setCount] = useState(0);

  return (
    div>
      p>Count: {count}/p>
      button onClick={() => setCount(count + 1)}>Increment/button>
    /div>
  );
}

export default Counter;

In this example, we have a functional component Counter that uses the useState Hook to add state to the component. The initial state of count is set to 0, and when the button is clicked, the count is incremented by 1.

2. useEffect Hook

useEffect is a built-in React Hook that allows you to perform side effects in function components.

Syntax

import React, { useEffect } from 'react';

    useEffect(() => {
        // Side effect code here
        return () => {
            // Cleanup code here
        };
    }, [dependencies]);

The useEffect function takes two arguments:

  • A function that contains the side effect code
  • An optional array of dependencies

The second argument, the dependencies array, is used to control when the side effect runs. If the dependencies array is empty, the side effect will only run once after the initial render. If dependencies are specified, the side effect will run whenever any of the dependencies change.

Code Implementation

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

    const ExampleComponent = () => {
        const [count, setCount] = useState(0);

        useEffect(() => {
            document.title = `You clicked ${count} times`;
        }, [count]);

        return (
            div>
                p>You clicked {count} times/p>
                button onClick={() => setCount(count + 1)}>Click me/button>
            /div>
        );
    };

In this example, the document title is updated based on the count state variable every time it changes.

Important Use Cases

  • Fetching data from an API
  • Subscribing to external events
  • Updating the DOM directly
  • Cleanup activities like removing event listeners

Further Reading

  1.  Common Pitfalls of useEffect Hook in React

3. useRef Hook

useRef is a Hook in React that allows you to keep mutable values in the functional components across renders without causing re-renders.

Syntax

The syntax for useRef is:

const myRef = useRef(initialValue);

Code Implementation

Here is an example of using useRef in a React component:

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

const MyComponent = () => {
  const inputRef = useRef(null);

  useEffect(() => {
    inputRef.current.focus();
  }, []);

  return (
    input ref={inputRef} type="text" />
  );
};

export default MyComponent;

Important Use-Cases

Some important use-cases of useRef include:

  • Accessing DOM elements directly
  • Storing previous values to compare with new values
  • Preserving values across re-renders without causing re-renders

Further Reading

  1. useRef vs createRef() in React
  2. useRef vs useState Hook in React

4. useContext Hook

useContext is a React Hook that allows components to subscribe to a context and access its value within the function body. It provides a way to pass data through the component tree without having to pass props down manually at every level.

Syntax

The syntax for useContext is:

const value = useContext(MyContext);

Code Implementation

Here is an example of how to use useContext in a React component:

import React, { useContext } from 'react';

const ThemeContext = React.createContext('light');

const ThemeProvider = ({ children }) => (
  ThemeContext.Provider value="dark">
    {children}
  /ThemeContext.Provider>
);

const App = () => {
  const theme = useContext(ThemeContext);
  
  return div>Current Theme: {theme}/div>;
};

Important Use-Cases

The useContext hook is commonly used in scenarios where:

  • There is a need to access global data or state across multiple components.
  • Reducing prop-drilling in deeply nested component trees.
  • Implementing themes, user authentication, or language preferences that are shared across the application.

5. useReducer Hook

useReducer is a built-in React Hook that offers a way to manage state transitions in a more complex manner compared to useState. It is particularly useful when the state logic involves multiple sub-values or when the next state depends on the previous one.

Syntax

The syntax of useReducer is as follows:

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

Here,

  • state: The current state value
  • dispatch: A function to dispatch actions
  • reducer: A function that specifies how the state should change based on the action
  • initialState: The initial state value

Example Code Implementation

Let's consider an example where we use useReducer to manage a counter:

import React, { useReducer } from 'react';

const initialState = { count: 0 };

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

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    div>
      Count: {state.count}
      button onClick={() => dispatch({ type: 'increment' })}>Increment/button>
      button onClick={() => dispatch({ type: 'decrement' })}>Decrement/button>
    /div>
  );
}

export default Counter;

Covering Important Use-Cases

  1. Managing complex state logic: useReducer is helpful when dealing with state objects that contain multiple sub-values or when the state logic is more intricate.
  2. State transitions based on previous state: When the next state depends on the previous one, useReducer provides a clean way to handle such scenarios.
  3. Optimizing performance: In some cases, using useReducer can help optimize performance by avoiding multiple re-renders that might occur with multiple useState calls.

Further Reading

  1. useState vs useReducer Hook in React

6. useMemo Hook

useMemo is a React Hook that allows you to memoize expensive calculations and cache the results. It helps in optimizing performance by preventing unnecessary re-renders.

Syntax

The basic syntax of useMemo is:

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

Here, computeExpensiveValue is the function whose result needs to be memoized, and [a, b] is the dependency array.

Example Code Implementation

Here is an example demonstrating the use of useMemo:

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

const App = () => {
  const [num1, setNum1] = useState(5);
  const [num2, setNum2] = useState(10);

  const sum = useMemo(() => {
    console.log('Calculating sum...');
    return num1 + num2;
  }, [num1, num2]);

  return (
    div>
      p>Number 1: {num1}/p>
      p>Number 2: {num2}/p>
      p>Sum: {sum}/p>
    /div>
  );
};

export default App;

Important Use-Cases

  • When a component needs to perform complex calculations that are based on certain props or state values.
  • When a component re-renders frequently due to changes in props or state, and you want to optimize performance by memoizing the result.
  • For optimizing performance in computationally heavy applications where calculations can be cached.

Further Reading

  1. React.memo vs useMemo
  2. useMemo vs useCallback
  3. useMemo vs useEffect Hooks in React

7. useCallback Hook

The useCallback Hook in React is used to memoize functions, which helps in preventing unnecessary re-renders in functional components. It is particularly useful when passing callbacks to child components that rely on reference equality to prevent unnecessary renders.

Syntax:

const memoizedCallback = useCallback(() => {
  // function body
}, [dependencies]);
  • memoizedCallback: The memoized callback function.
  • useCallback: The Hook function.
  • dependencies: An array of dependencies. The callback will only be re-created if one of these dependencies changes.

Example Code Implementation:

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

const App = () => {
  const [count, setCount] = useState(0);

  const handleClick = useCallback(() => {
    setCount(count + 1);
  }, [count]);

  return (
    div>
      p>Count: {count}/p>
      button onClick={handleClick}>Increment/button>
    /div>
  );
};

export default App;

In this example, the handleClick function is memoized using useCallback. It depends on the count state, so it will only be re-created if count changes.

Important Use-Cases:

  1. Optimizing performance: Use useCallback when passing callbacks to child components to avoid unnecessary renders.
  2. Preventing infinite loops: In cases where a callback function is used inside useEffect, useCallback can prevent infinite loops caused by changing the function reference on each render.
  3. Referential equality: When identity comparison is important, such as in React.memo or useMemo, useCallback ensures the same callback instance is used.

8. useLayoutEffect Hook

useLayoutEffect is similar to useEffect but it fires synchronously after all DOM mutations. This can be useful when you need to read from the DOM and then immediately perform a synchronous action that affects the DOM.

Syntax

import React, { useLayoutEffect } from 'react';

useLayoutEffect(() => {
    // Effect code here
}, [dependencies]);

Example Code Implementation

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

const ExampleComponent = () => {
    const [width, setWidth] = useState(0);

    useLayoutEffect(() => {
        const updateWidth = () => {
            setWidth(window.innerWidth);
        };

        window.addEventListener('resize', updateWidth);

        return () => window.removeEventListener('resize', updateWidth);
    }, []);

    return (
        div>
            Current Width: {width}px
        /div>
    );
};

Important Use-Cases

  • Measure DOM elements: When you need to measure a DOM element and perform actions based on those measurements.
  • Perform imperative DOM actions: When you need to perform synchronous DOM actions immediately after a render.
  • Optimizing performance: When you want to ensure that your effects run synchronously to prevent flickering or layout shifts.

Further Reading

  1. useEffect vs useLayoutEffect Hook in React

9. useId Hook

useId Hook is a custom React Hook used to generate unique IDs for elements within a component.

Syntax

const uniqueId = useId(prefix);

Parameters:

  • prefix (optional): A string value to be used as a prefix for the generated ID.

Example Code Implementation

import React from 'react';
import { useId } from 'react-id-generator';

const MyComponent = () => {
    const uniqueId = useId();

    return (
        div id={uniqueId}>
            p>Unique ID: {uniqueId}/p>
        /div>
    );
};

export default MyComponent;

Important Use-Cases

  1. Accessibility: Generating unique IDs for form labels and inputs to improve accessibility by associating them correctly.
  2. Conditional Rendering: When rendering dynamic lists or components, useId ensures each element has a unique identifier.
  3. Styling: Assigning unique IDs to elements for targeted styling using CSS or JS

Further Reading

  1. Difference between React useId hook and generating IDs using Math.random

10. useTransition Hook

useTransition is a React hook that allows you to animate the entering and leaving of elements in a list. It helps in creating smooth transitions when adding or removing items.

Syntax

The syntax for useTransition is:

const [items, setItems] = useState([]);
const transitions = useTransition(items, {
  from: { opacity: 0 },
  enter: { opacity: 1 },
  leave: { opacity: 0 }
});

Example Code

Here is an example demonstrating the use of useTransition:

import React, { useState } from 'react';
import { useTransition, animated } from 'react-spring';

const App = () => {
  const [items, setItems] = useState([]);

  const transitions = useTransition(items, {
    from: { opacity: 0 },
    enter: { opacity: 1 },
    leave: { opacity: 0 }
  });

  return (
    div>
      button onClick={() => setItems([...items, { id: items.length, text: 'Item ' + items.length }])}>
        Add Item
      /button>
      {transitions((style, item) => (
        animated.div style={style}>{item.text}/animated.div>
      ))}
    /div>
  );
};

export default App;

Important Use-Cases

  • Dynamic List Animations: useTransition is ideal for animating dynamic lists where items are added or removed.
  • Smooth UI Interactions: It helps in creating a smoother user interface by animating changes in the DOM.
  • Enhancing User Experience: Animating transitions can enhance the overall user experience of an application.

11. useDeferredValue Hook

useDeferredValue is a React hook that allows you to defer a value update for a specified amount of time to improve the performance of a component.

Syntax

const deferredValue = useDeferredValue(value, options);

Parameters:

  • value: The value to be deferred.
  • options: An object with the following optional properties:
  • timeoutMs: The time in milliseconds to defer the update.
  • startTransition: A function that can be used to start a transition.

Example

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

const App = () => {
    const [count, setCount] = useState(0);

    const deferredCount = useDeferredValue(count, { timeoutMs: 2000 });

    return (
        <div>
            <button onClick={() => setCount(count + 1)}>Increment Count</button>
            <p>Deferred Count: {deferredCount}</p>
        </div>
    );
};

In this example, the deferredCount will be updated only after 2000 milliseconds (2 seconds) have elapsed since the last change in count.

Important Use Cases

  1. Reducing UI Jank: Defer expensive updates to prevent blocking the main thread and improve user experience.
  2. Optimizing Performance: Use deferred values for non-critical updates to avoid unnecessary re-renders.

Further Reading:

  1. useDeferredValue vs useTransition Hook in React

12. useImperativeHandle Hook

useImperativeHandle is a React hook that allows a parent component to access functions or values of a child component through a ref. This hook is useful when you want to expose certain imperative methods of a child component to its parent, thereby enabling more control over the child component from the parent.

Syntax

useImperativeHandle(ref, () => ref.current, [dependencies]);
  • ref: Ref object created using useRef.
  • dependencies: Optional parameter that triggers the update of the returned value when any of the dependencies change.

Example Code Implementation

import React, { useRef, useImperativeHandle, forwardRef } from 'react';

const ChildComponent = forwardRef((props, ref) => {
  const internalFunction = () => {
    console.log('Internal function called');
  };

  useImperativeHandle(ref, () => ({
    exposeFunction: internalFunction
  }));

  return <div>Child Component</div>;
});

const ParentComponent = () => {
  const childRef = useRef();

  const handleClick = () => {
    childRef.current.exposeFunction();
  };

  return (
    <div>
      <ChildComponent ref={childRef} />
      <button onClick={handleClick}>Call Child Function</button>
    </div>
  );
};

export default ParentComponent;

In this example, ChildComponent exposes an internal function using useImperativeHandle which can be accessed by the parent component ParentComponent through a ref.

Important Usecases

  1. Encapsulation: Allows hiding implementation details of child components while exposing specific functionalities.
  2. Refactoring: Useful when refactoring components to maintain backward compatibility by exposing the same interface.
  3. Integration with External Libraries: Facilitates integration with third-party libraries that require direct access to component methods or properties.

13. useSyncExternalStore Hook

The useSyncExternalStore hook is a custom React hook that allows synchronizing the local state of a component with an external store (e.g., local storage, session storage, etc.). This can be useful for persisting state across page reloads or sharing state between different components.

Syntax

const [state, setState] = useSyncExternalStore(key, initialValue);
  • key: A unique string key to identify the data in the external store.
  • initialValue: The initial value for the state.

Example Implementation

import React from 'react';
import { useSyncExternalStore } from './useSyncExternalStore';

const App = () => {
  const [count, setCount] = useSyncExternalStore('count', 0);

  const increment = () => setCount(count + 1);
  const decrement = () => setCount(count - 1);

  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </div>
  );
};

export default App;

Important Use Cases

  1. Persisting User Preferences: Storing user preferences such as theme settings, language selection, etc., in local storage.
  2. Form Data Persistence: Saving form data temporarily in session storage to prevent data loss on page refresh.
  3. Shared State Management: Sharing state between different components that are not directly related.

Further Reading 🚀

  1. 100+ Top React JS Interview Questions and Answers
  2. Top 30 Frequently Asked React Hooks Interview Questions
  3. 20 Most Asked Custom Hooks in React
  4. 8 Must-Know React Hook Comparisons for Interviews
  5. Best Resources for React Interview Preparation

Love this Blog? Share it Now!

Help others discover this resource

About the Author

Anuj Sharma

A seasoned Sr. Engineering Manager at GoDaddy (Ex-Dell) with over 12+ years of experience in the frontend technologies. A frontend tech enthusiast passionate building SaaS application to solve problem. Know more about me  🚀


Learn Next

Featured

100+ Top React JS Interview Questions And Answers

20 Most Asked Custom Hooks in React for InterviewsTop 10 React Performance Optimization Techniques25 Top JavaScript Interview Questions for BeginnersHow to create custom useInfiniteScroll Hook in ReactImplement useThrottle Custom Hook In React

Comments

Be the first to share your thoughts!

Guest User

Please login to comment

0 characters


No comments yet.

Start the conversation!

About the Author

Anuj Sharma

A seasoned Sr. Engineering Manager at GoDaddy (Ex-Dell) with over 12+ years of experience in the frontend technologies. A frontend tech enthusiast passionate building SaaS application to solve problem. Know more about me  🚀

Share your expertise

Publish a blog or quick notes on topics you know well — your write-up could be the answer someone needs before their next frontend interview.

Build your portfolio

Help the community

Sharpen your skills

Earn goodies

Other Related Blogs

Top 30 Frequently Asked React Hooks Interview Questions (2026)

Anuj Sharma

Last Updated Jun 27, 2026

Discover the top 30 most-asked React Hooks Interview Questions, with detailed explanations and code examples for quick revision.

8 React Hooks Comparisons: Must Know for Frontend Interviews

Anuj Sharma

Last Updated Jun 26, 2026

Explore the Most Common React Hooks Comparisons and Trade-Offs to understand the differences between Hooks & When to use one hook over another.

Common Pitfalls of useEffect Hook: Must Know for React Devs?

Anuj Sharma

Last Updated Jun 24, 2026

Understand common pitfalls of the useEffect hook when implementing asynchronous operations in React applications effectively.

useMemo vs useEffect Hooks in React: Difference & Trade-Off

Anuj Sharma

Last Updated Jun 24, 2026

Explore useMemo vs useEffect in React with examples. Learn key differences between useMemo and useEffect, use cases, and when to choose one hook over the other in React applications and interviews.

Difference between React useId Hook and generating IDs using Math.random?

Anuj Sharma

Last Updated Jun 24, 2026

Understand the difference between using useId() vs generating IDs using Math.random() to better know the practical use-case of useId Hook in react applications.

useDeferredValue vs useTransition: Difference and Trade-Off

Anuj Sharma

Last Updated Jun 20, 2026

Explore useDeferredValue vs useTransition in React with examples. Learn key differences between useDeferredValue and useTransition, use cases and when to choose one over the other in React applications.

useRef vs useState in React: Difference & Trade-off

Anuj Sharma

Last Updated Jun 19, 2026

Explore useRef vs useState in React with examples. Learn the key differences between useRef and useState, use cases, advantages, and disadvantages, and when to choose one over the other in React applications.

useRef vs createRef in React: Difference and Trade Off

Anuj Sharma

Last Updated Jun 19, 2026

Explore useRef vs createRef in React with examples. Learn the key differences between useRef and createRef, use cases and when to choose one over the other in React applications

Stay Updated

Subscribe to FrontendGeek Hub for frontend interview preparation, interview experiences, curated resources and roadmaps.

FrontendGeek
FrontendGeek

All in One Preparation Hub to Ace Frontend Interviews. Master JavaScript, React, System Design, and more with curated resources.

Consider Supporting this Free Platform

Buy Me a Coffee

Product

HomeFrontend InterviewFrontend JobsQuestionsNewInterview ExperienceBlogsToolsLeaderboardFrontendGeek Chrome extensionGet the extension on the Chrome Web Store →

© 2026 FrontendGeek. All rights reserved