Search Tutorials


Top React Hooks (2025) frequently asked interview questions | JavaInUse

Top React Hooks frequently asked interview questions


In this post we will look at React Hooks Interview questions. Examples are provided with explanation.


  1. Using React is it possible to initialize state from a function? Please provide an example.
  2. What is the purpose of componentWillMount() in React Hooks?
  3. What are React Hooks used for?
  4. What lifecycle methods of class components do useEffect replace in functional components?
  5. When is it best to use useRef?
  6. How does React.memo() compare to useMemo()?
  7. How can I use the React useEffect hook to call a loading function only once?
  8. How can Error Boundaries be implemented in functional React components?
  9. Can you give an example of a simple Custom React Hook, and why do we need them?
  10. How does useState() work in React?
  11. What is the method for accessing DOM elements in React?

Using React is it possible to initialise state from a function? Please provide an example.

Yes, it is possible to initialize state from a function in React. Here's an example:
const MyComponent = () => {
  const [state, setState] = useState(() => {
    return {
      count: 0,
      otherData: 'some data'
    };
  });
  
  // The count and otherData in state will initially be set to 0 and 'some data' respectively
};


What is the purpose of componentWillMount() in React Hooks?

The componentWillMount() hook in React Hooks is used to perform setup operations before the component is mounted. This hook is invoked before the initial render of a component and allows the users to perform any operations prior to the component being mounted on the DOM. It can be used to prepare data, set up timers, fetch API data, add event listeners, and more. The information from this hook will also persist between re-renders, so its use can help improve performance by avoiding unnecessary re-fetching of data. Here is an example code snippet:
const App = () => {
  useEffect(() => {
    // Do something before the component mounts
    console.log('componentWillMount')
    fetchData();

    // Return a function if needed to be invoked when unmounting
    return () => console.log('componentWillUnmount');
  }, []);

  return <div>An example component</div>;
};

What are React Hooks used for?

React Hooks are a new feature in React that let you use state and other features in functional components. They provide an alternative to writing class-based components, and allow you to write cleaner, more concise code. Hooks let you easily access state, perform side effects, and write custom logic in functional components. React provides several built-in Hooks, including useState(), useEffect(), useContext(), and useReducer(). Here is an example of how to use the useState() Hook to add a counter to a functional component:
  const [count, setCount] = useState(0);

  function handleClick() {
    setCount(count + 1);
  }

  return (
    <div>
      <h1>Counter App</h1>
      <p>You clicked {count} times.</p>
      <button onClick={handleClick}>+</button>
    </div>
  );
  


What lifecycle methods of class components do useEffect replace in functional components?

In functional components, useEffect() replaces three of the main lifecycle methods of class components: componentWillMount(), componentDidMount(), and componentWillUnmount(). The useEffect() Hook performs the same tasks as these methods, but does so with a much simpler syntax. The useEffect() Hook takes a function as an argument and runs it after every render. This allows you to perform side effects like fetching data, or setting up a subscription. Here is an example of how to use useEffect() to fetch data from an API in a functional component:
useEffect(() => {
  fetch('https://example.com/api')
    .then(res => res.json())
    .then(data => setData(data));
}, []);
In the example above, useEffect() will run the function after every render. The second argument to useEffect() is an array that specifies when the effect should be run. In this case, we have passed an empty array, which tells useEffect() to run the effect only once, when the component is mounted.

When is it best to use useRef?

useRef can be used when you need to access a DOM element or an instance of a class component directly. To illustrate, let us say you have a class component called Clock that displays the current time. If you wanted to update the time displayed on the clock, you would need to access the instance of Clock in order to call the function that updates the time. In this case, useRef would be the perfect solution. To use useRef, start by declaring a variable with the useRef hook. You can give the variable any name you want, but it is typically best to name it after the element you are referencing (in our example, we would call it clockRef).
// Declare the variable with the useRef hook
const clockRef = useRef();

// Set the variable to reference an element
<Clock ref={clockRef} />

// Use the variable to access the element
clockRef.current.updateTime();
By using useRef, you can access the instance of Clock and its functions without needing to use props to pass data back up the component tree. This can help make your application's codebase much more efficient and maintain

How does React.memo() compare to useMemo()?

React.memo() and useMemo() are both React features that allow you to optimize your application's performance by caching values and avoiding unnecessary re-renders. The main difference between the two is that React.memo() is used to wrap React components, while useMemo() is used to wrap functions. React.memo() is used to wrap React components and memoize them, meaning that if the props passed to the component do not change, the component will not re-render. This can be a great way to optimize your application's performance, as it avoids unnecessary re-renders and can help improve the overall user experience.
// Wrap a component in React.memo()
const MyComponent = React.memo(props => {
  // Component code
});
useMemo() is used to wrap functions and memoize their return values. This can be useful when you have a function that is computationally expensive and you want to avoid running it every time the component re-renders.
// Wrap a function in useMemo()
const expensiveFunction = useMemo(() => {
  // Function code
},






How can I use the React useEffect hook to call a loading function only once?

You can use the React useEffect hook to call a loading function only once by passing an empty array as the second argument. When you provide an empty array as the second argument to the useEffect hook, it ensures that the callback passed to useEffect is invoked only once, when the component mounts for the first time. Here is an example code snippet:
const App = () => {
  useEffect(() => {
    // Function to be called only once when component mounts
    loadData();
  }, []);

  return <div>An example component</div>;
};


How can Error Boundaries be implemented in functional React components?

Error boundaries can be implemented in functional React components using the useErrorBoundary hook. The useErrorBoundary hook takes a callback function as its argument, which will be called if an error occurs within the component. Inside the callback function, you can provide logic to handle errors and alert the user of the errors. Here is an example code snippet:
const App = () => {
    const [error, setError] = useErrorBoundary(err => {
        // Logic to handle any errors that occur within the component 
        console.log(err);
        alert('An error has occurred!');
    });

    return (
        <div>
            <p>An example component</p>
            {error && <p>An error has occurred!</p>}
        </div>
    );
};


Can you give an example of a simple Custom React Hook, and why do we need them?

Custom React hooks can be used to extract reusable logic from components, which makes the components easier to maintain and improve. Here is an example of a simple custom React hook:
const useCounter = () => {
  const [count, setCount] = useState(0);
  
  const increment = () => {
    setCount(count + 1);
  }

  return {
    count,
    increment
  }
}

// Usage
const Counter = () => {
  const { count, increment } = useCounter();
  return <button onClick={increment}>{count}</button>;
};
This custom hook allows us to reuse the logic related to handling and displaying a count, so it can be easily exported and shared across multiple components.

How does useState() work in React?

useState() is a built-in React Hook that lets you use state in your functional components. It represents an individual piece of state data in your React app. When you call useState(), React will preserve that state between re-renders. The function returns an array with two values: the current value of the state and a function that lets you update it. You can think of useState() as a box in your code that holds a single value. To update the value in the box, you call the function returned from useState(). Here is a basic example of how to use useState() for a simple counter app:

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

return (
   <div>
      <h1>Counter App</h1>
      <p>You clicked {count} times.</p>
      <button onClick={() => setCount(count + 1)}>+</button>
   </div>
);
In the example above, we use useState() to store the number of button clicks in a count variable. We also assign a function, setCount(), which takes in the new count

What is the method for accessing DOM elements in React?

Accessing DOM elements in React is done through the use of the React ref API. This API provides a way to create and interact with React reference objects. You can create a reference by passing an existing DOM element or a callback to the ref attribute of a React element. When a ref is passed to an element, a reference to the node becomes accessible at the current attribute of the ref. In the following example, we use the ref API to access a DOM element in a React functional component:
const myRef = React.createRef();

const MyComponent = () => {
  return (
    <div>
      <h1>My Component</h1>
      <div ref={myRef}>I am a div element!</div>
    </div>
  )
}

console.log(myRef.current); // <div>I am a div element!</div>
Using the ref API lets you work with any existing DOM element and provides a way to access it without needing to use IDs or query selectors. This is especially useful when working with stateful components and forms.

See Also

Spring Batch Interview Questions Apache Camel Interview Questions JBoss Fuse Interview Questions Drools Interview Questions Java 8 Interview Questions