Sobes.tech
Middle

What other React hooks do you know? Tell about useRef, useReducer, useCallback, useMemo, useContext.

sobes.tech AI

Answer from AI

  • useRef — allows creating a mutable object that persists across renders. It is commonly used to access DOM elements or store mutable values without causing a re-render.

  • useReducer — an alternative to useState for more complex state logic, especially when there are multiple related values or complex transitions. It works on the principle of a reducer from Redux.

  • useCallback — memoizes a function so that it is not recreated on every render if dependencies haven't changed. Useful for optimization and preventing unnecessary re-renders of child components.

  • useMemo — memoizes a computed value to avoid recalculating it on every render if dependencies haven't changed.

  • useContext — allows accessing a value from React Context without passing props through all component levels.

Example of using useRef to access an input:

import React, { useRef } from 'react';

function TextInput() {
  const inputRef = useRef(null);

  const focusInput = () => {
    inputRef.current.focus();
  };

  return (
    <>
      <input ref={inputRef} type="text" />
      <button onClick={focusInput}>Focus on input</button>
    </>
  );
}