React Interview Questions

39 Questions
React.js

React.js

FrontendWeb Development

Question 14

What are hooks in React? Can you name a few commonly used hooks?

Answer:

Hooks in React are special functions that allow you to use state and other React features in functional components. They provide a way to reuse stateful logic without changing the component hierarchy. Hooks were introduced in React 16.8 and have since become a fundamental part of writing React applications.

Commonly Used Hooks

  1. useState

    • Allows you to add state to functional components.
    • Syntax: const [state, setState] = useState(initialState);
    import React, { useState } from 'react';
    
    function Counter() {
      const [count, setCount] = useState(0);
    
      return (
        <div>
          <p>You clicked {count} times</p>
          <button onClick={() => setCount(count + 1)}>Click me</button>
        </div>
      );
    }
  2. useEffect

    • Performs side effects in functional components (e.g., data fetching, subscriptions).
    • Replaces lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.
    • Syntax: useEffect(() => { /* effect */ }, [dependencies]);
    import React, { useEffect, useState } from 'react';
    
    function Example() {
      const [count, setCount] = useState(0);
    
      useEffect(() => {
        document.title = `You clicked ${count} times`;
      }, [count]); // Only re-run the effect if count changes
    
      return (
        <div>
          <p>You clicked {count} times</p>
          <button onClick={() => setCount(count + 1)}>Click me</button>
        </div>
      );
    }
  3. useContext

    • Allows you to access the value of a context.
    • Syntax: const value = useContext(MyContext);
    import React, { useContext } from 'react';
    
    const MyContext = React.createContext();
    
    function MyComponent() {
      const value = useContext(MyContext);
      return <div>{value}</div>;
    }
    
    function App() {
      return (
        <MyContext.Provider value="Hello, World!">
          <MyComponent />
        </MyContext.Provider>
      );
    }
  4. useReducer

    • An alternative to useState for managing complex state logic.
    • Similar to Redux's reducer function.
    • Syntax: const [state, dispatch] = useReducer(reducer, initialState);
    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>
          <p>Count: {state.count}</p>
          <button onClick={() => dispatch({ type: 'increment' })}>+</button>
          <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
        </div>
      );
    }
  5. useRef

    • Provides a way to access and manipulate DOM elements directly.
    • Holds a mutable reference to a DOM element that persists across renders.
    • Syntax: const ref = useRef(initialValue);
    import React, { useRef } from 'react';
    
    function FocusInput() {
      const inputRef = useRef(null);
    
      const focusInput = () => {
        inputRef.current.focus();
      };
    
      return (
        <div>
          <input ref={inputRef} type="text" />
          <button onClick={focusInput}>Focus the input</button>
        </div>
      );
    }
  6. useMemo

    • Memoizes a computed value, recomputing it only when dependencies change.
    • Optimizes performance by preventing unnecessary calculations.
    • Syntax: const memoizedValue = useMemo(() => computeValue(a, b), [a, b]);
    import React, { useMemo, useState } from 'react';
    
    function ExpensiveComputationComponent({ a, b }) {
      const memoizedValue = useMemo(() => {
        return computeExpensiveValue(a, b);
      }, [a, b]);
    
      return <div>{memoizedValue}</div>;
    }
    
    function computeExpensiveValue(a, b) {
      // Expensive computation
      return a + b;
    }
  7. useCallback

    • Returns a memoized callback function that only changes if dependencies change.
    • Useful for optimizing child component re-renders by ensuring stable function references.
    • Syntax: const memoizedCallback = useCallback(() => { doSomething(a, b); }, [a, b]);
    import React, { useCallback, useState } from 'react';
    
    function ParentComponent() {
      const [count, setCount] = useState(0);
    
      const increment = useCallback(() => {
        setCount(count + 1);
      }, [count]);
    
      return <ChildComponent onClick={increment} />;
    }
    
    function ChildComponent({ onClick }) {
      return <button onClick={onClick}>Increment</button>;
    }

Conclusion

Hooks in React provide powerful and flexible tools for managing state, side effects, context, and more in functional components. They enable developers to write cleaner, more modular code and avoid the pitfalls associated with class components. Some of the most commonly used hooks include useState, useEffect, useContext, useReducer, useRef, useMemo, and useCallback. Each of these hooks addresses specific needs and use cases, making it easier to manage and optimize React applications.

Recent job openings