React  

Mastering React Hooks: Types, Real-World Use Cases

React introduced Hooks in version 16.8 to simplify component logic and state management without relying on class components. Hooks allow developers to use state, lifecycle methods, and side effects directly inside functional components, making code cleaner, reusable, and easier to test.

Why Use Hooks in React?

  1. Simplify Code – Replace bulky class components with lightweight functions.

  2. Reusability – Encapsulate logic in custom hooks and share across components.

  3. Better Readability – No need for this or lifecycle method confusion.

  4. Performance – Reduce unnecessary re-renders with hooks like useMemo and useCallback.

  5. Migration Friendly – Helps modernize old React apps.

Types of React Hooks

1. Basic Hooks

✅ useState

  • Manages local state in a functional component.
    Use Case: Toggle a dark/light theme.

const [theme, setTheme] = useState("light");

✅ useEffect

  • Handles side effects (API calls, subscriptions, DOM manipulation).
    Use Case: Fetch user data on component load.

useEffect(() => {
  fetchUserData();
}, []);

✅ useContext

  • Access global state without prop drilling.
    Use Case: Multi-theme or multi-language support across the app.

const theme = useContext(ThemeContext);

2. Additional Hooks

✅ useReducer

  • Alternative to useState for complex state logic.
    Use Case: Shopping cart with add/remove operations.

const [state, dispatch] = useReducer(cartReducer, initialCart);

✅ useRef

  • Directly reference DOM elements or persist values between renders.
    Use Case: Focus input field on form load.

const inputRef = useRef();
useEffect(() => inputRef.current.focus(), []);

✅ useMemo

  • Memoizes computed values to avoid expensive recalculations.
    Use Case: Optimizing a search filter in large datasets.

const filteredData = useMemo(() => data.filter(d => d.includes(query)), [query]);

✅ useCallback

  • Memoizes functions to prevent unnecessary re-renders.
    Use Case: Pass stable callback props to child components.

const handleClick = useCallback(() => doSomething(), []);

✅ useLayoutEffect

  • Similar to useEffect but runs before painting the UI.
    Use Case: Measuring DOM size before rendering a tooltip.

✅ useImperativeHandle

  • Customize ref behavior when using forwardRef.
    Use Case: Expose only specific methods from a child component (like resetForm).

3. Custom Hooks

  • A custom hook is just a function starting with use that encapsulates reusable logic.
    Use Case: useAuth() to handle login/logout/session checks.

function useAuth() {
  const [user, setUser] = useState(null);
  useEffect(() => {
    const loggedInUser = localStorage.getItem("user");
    if (loggedInUser) setUser(JSON.parse(loggedInUser));
  }, []);
  return user;
}

Real-World Scenarios

  1. E-Commerce Website

    • useReducer: Manage cart operations (add/remove/update items).

    • useEffect: Fetch product list from API.

    • useContext: Share user authentication state across app.

  2. Social Media App

    • useState: Manage likes/comments count.

    • useEffect: Poll notifications from server.

    • useMemo: Optimize feed rendering.

  3. Video Streaming Platform

    • useRef: Control video play/pause/volume.

    • useCallback: Stable handlers for play/pause buttons.

  4. Banking Application

    • useReducer: Manage complex transaction states.

    • useEffect: Auto-logout on session timeout.

React Hooks Interview Questions and Answers

Q1. Why were hooks introduced in React?

Answer: To simplify state and lifecycle management in functional components, reduce complexity, and improve reusability without converting everything into class components.

Q2. Difference between useState and useReducer?

Answer:

  • useState: For simple, local state.

  • useReducer: For complex state logic with multiple transitions (like Redux-style state).

Q3. What is the difference between useEffect and useLayoutEffect?

Answer:

  • useEffect: Runs asynchronously after painting the UI.

  • useLayoutEffect: Runs synchronously before painting, useful for DOM measurements.

Q4. How do useMemo and useCallback differ?

Answer:

  • useMemo: Caches computed values.

  • useCallback: Caches functions.

Q5. Can hooks be used in class components?

Answer: No, hooks only work in functional components.

Q6. What are rules of hooks?

Answer:

  1. Only call hooks at the top level (not inside loops, conditions, or nested functions).

  2. Only call hooks from React functional components or custom hooks.

Q7. Example of a custom hook?

Answer: useAuth, useFetch, useLocalStorage are popular custom hooks for reusability.

✅ Final Tip : Always explain hooks with real-world use cases (cart, login, API fetch, notifications, etc.), not just definitions. This shows practical understanding.