logo
React Hooks - Interview Questions and Answers
What are React Hooks?
React Hooks are a feature introduced in React 16.8 that allow developers to use state and other React features in functional components, without needing to write class components. They’re essentially functions that "hook into" React’s internals, enabling you to manage state, side effects, and other lifecycle-like behaviors in a more concise and reusable way.

Before Hooks, state and lifecycle methods (like componentDidMount or setState) were tied to class components, which could get clunky and hard to maintain, especially with complex logic. Hooks solve this by letting you write everything as functions, making code cleaner and easier to share between components.

Here’s a quick rundown of the main ones:

useState : Lets you add state to a functional component. You call it with an initial value, and it returns an array with the current state and a function to update it. Example :
import React, { useState } from 'react';
function Counter() {
  const [count, setCount] = useState(0);
  return  setCount(count + 1)}>{count};
}?

 

useEffect: Handles side effects—like data fetching, subscriptions, or DOM updates—similar to lifecycle methods in classes. It runs after every render by default, but you can control it with a dependency array. Example :
import React, { useEffect } from 'react';
function Example() {
  useEffect(() => {
    document.title = 'Hello, world!';
  }, []); // Empty array means it runs once on mount
  return <div>Check the title!</div>;
}

useContext
: Lets you access React’s context (global-ish state) without prop drilling. Useful for themes, user data, etc.
const value = useContext(MyContext);?

There are others too, like useReducer (for complex state logic), useCallback (memoizes functions), and useMemo (memoizes values), plus you can create custom Hooks to reuse logic across components.