DEV Community

Cover image for React Hooks Interview Questions for Freshers
Sudhanshu Gaikwad
Sudhanshu Gaikwad

Posted on

React Hooks Interview Questions for Freshers

React Hooks have revolutionized the way we manage state and side effects in functional components. Here are ten essential interview questions about React Hooks that every fresher should know, along with straightforward answers to help you prepare for your next interview!

1. What are React Hooks?
Answer: React Hooks are functions that allow you to use state and lifecycle features in functional components. They were introduced in React 16.8 and provide a way to manage component logic without the need for class components.

2. What is the useState Hook, and how does it work?
Answer: The useState Hook lets you add state to functional components. It returns an array with two elements: the current state value and a function to update that state. For example:

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

Enter fullscreen mode Exit fullscreen mode

Here, count is the state variable, and setCount is the function to update it.

3. Explain the useEffect Hook and its purpose.
Answer: The useEffect Hook allows you to perform side effects in functional components. This includes tasks like data fetching, subscriptions, and manually changing the DOM. You can control when the effect runs by specifying a dependency array. Here's a simple example:

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

const DataFetcher = () => {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => setData(data));
  }, []); // Runs only once after the initial render

  return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>;
};


Enter fullscreen mode Exit fullscreen mode

4. What is the difference between useEffect and useLayoutEffect?
Answer: Both useEffect and useLayoutEffect are Hooks used for side effects, but they differ in timing:

  • useEffect: Runs asynchronously after the DOM has been updated. It's ideal for tasks that don't need immediate updates, such as fetching data or setting up subscriptions.
  • useLayoutEffect: Runs synchronously after all DOM mutations but before the browser has a chance to paint. Use it for tasks that require immediate updates to the DOM, like measuring layout.

5. How do you use multiple state variables with useState?
Answer: You can call useState multiple times in the same component to manage different state variables. For example:

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

Enter fullscreen mode Exit fullscreen mode

This allows you to manage count and name independently.

6. What are custom Hooks? How do you create one?
Answer: A custom Hook is a JavaScript function that can use built-in Hooks. It allows you to encapsulate logic and reuse it across multiple components. You simply create a function that starts with "use" and calls other Hooks inside it. For example:

import { useState } from 'react';

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

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

  return { count, increment, decrement }; // Returns the count and functions to update it
};

// Usage in a component
const CounterComponent = () => {
  const { count, increment, decrement } = useCounter(10); // Starts from 10

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


Enter fullscreen mode Exit fullscreen mode

7. When should you use useMemo and useCallback?
Answer: : Both useMemo and useCallback are optimization Hooks that help prevent unnecessary re-renders:
useMemo: Used to memoize the result of a calculation. It recalculates the value only when its dependencies change, which is useful for expensive calculations.

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

Enter fullscreen mode Exit fullscreen mode

useCallback: Used to memoize a function. It returns a memoized version of the function that only changes if one of the dependencies has changed, preventing the function from being recreated on every render.

const memoizedCallback = useCallback(() => {
  doSomething(a, b);
}, [a, b]);

Enter fullscreen mode Exit fullscreen mode

These Hooks are especially useful when passing functions or values to child components, preventing unnecessary renders and improving performance.

8. What is the purpose of the dependency array in useEffect?
Answer: The dependency array tells React when to run the effect. If you pass an empty array ([]), the effect runs only once after the initial render. If you include variables, the effect will run whenever those variables change.

9. Can you explain how to manage forms using Hooks?
Answer: You can manage forms using useState to track input values and handle changes. For example:

const [inputValue, setInputValue] = useState("");

const handleChange = (e) => {
  setInputValue(e.target.value);
};

return <input value={inputValue} onChange={handleChange} />;

Enter fullscreen mode Exit fullscreen mode

This setup keeps the input field's value in sync with the state.

10. What are some common pitfalls when using Hooks?
Answer: Common pitfalls include:

  • Forgetting to include dependencies in the useEffect dependency array, leading to stale data.
  • Using Hooks conditionally (e.g., inside if statements), which can cause issues with the order of Hooks calls.
  • Not cleaning up effects when using useEffect, leading to memory leaks.

Being well-versed in React Hooks is crucial for any fresher aspiring to become a Frontend Developer. Understanding these questions will not only help you during interviews but also strengthen your grasp of React concepts. Happy coding!

Top comments (0)