https://medium.com/womenintechnology/what-are-the-different-types-of-hooks-in-react-470fdeb86b9

위 글을 참고하여 쓴 글임을 알립니다.

What are the different types of hooks in React?

1. State Hooks

useState

가장 흔히 사용되는 리액트 훅입니다.

함수 컴포넌트에서 자체 상태 변수들을 지닐수 있게 합니다.

초기값을 인자로 받으며 두 개의 값을 가진 배열을 반환합니다.

현재 상태에 대한 값과 상태를 변화시키는 함수 입니다.

import React, { useState } from 'react';

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

  const increment = () => {
    setCount(count + 1);
  };

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

useReducer

복잡한 상태관리 로직을 다룰때에 useState의 대체 버전을 제공합니다.

예를들어 여러개의 하위 값을 가지고 있거나 다음 상태의 변화가 이전 상태의 값에 의존될 때 등입니다.

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 };
    case 'reset':
      return initialState;
    default:
      throw new Error('Unsupported action type');
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);

  const increment = () => {
    dispatch({ type: 'increment' });
  };

  const decrement = () => {
    dispatch({ type: 'decrement' });
  };

  const reset = () => {
    dispatch({ type: 'reset' });
  };

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

2. Effect Hooks

useEffect

data fetching, subscriptions, 컴포넌트가 렌더링 된 후의 DOM 조작과 같이 부가적인 effect들을 다룰때에 사용합니다.

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

function Example() {
  const [data, setData] = useState(null);

  useEffect(() => {
    // This effect runs after the component has rendered

    // Perform some asynchronous data fetching
    fetchData()
      .then((result) => {
        setData(result);
      })
      .catch((error) => {
        console.error('Error fetching data:', error);
      });

    // Clean up the effect
    return () => {
      // Perform any necessary cleanup here
      // This is optional but important to prevent memory leaks
    };
  }, []); // Empty dependency array, so the effect runs only once on component mount

  return <div>{data ? <p>Data: {data}</p> : <p>Loading data...</p>}</div>;
}

export default Example;

useLayoutEffect

useEffect와 비슷하지만, 모든 DOM 변화들이 적용 된 후에 동기적으로 실행됩니다.

레이아웃을 측정하거나 DOM 변화에 따른 동기적인 변화를 수행할때에 유용합니다.

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

function Example() {
  const [width, setWidth] = useState(0);

  useLayoutEffect(() => {
    // This effect runs synchronously after all DOM mutations
    // but before the browser paints

    const updateWidth = () => {
      const newWidth = document.documentElement.clientWidth;
      setWidth(newWidth);
    };

    // Add event listener for window resize
    window.addEventListener('resize', updateWidth);

    // Initial width update
    updateWidth();

    // Clean up the effect
    return () => {
      // Remove event listener
      window.removeEventListener('resize', updateWidth);
    };
  }, []); // Empty dependency array, so the effect runs only once on component mount

  return <div>Window width: {width}px</div>;
}

export default Example;

useEffectOnce

effect를 컴포넌트가 마운트 될 때에 한번만 사용하게 하도록 하는 커스텀한 훅입니다.

import React, {useEffect} from 'react;

function useEffectOnce(effect) {
	// do not include any dependency values on array
	useEffect(effect, []);
}

// Usage:
function Example() {
  useEffectOnce(() => {
    // This effect runs only once on component mount
    console.log('Effect ran only once');
  });

  return <div>Example Component</div>;
}

export default Example;

3. Context Hooks

useContext

이 훅은 리액트에서 리액트 컨텍스트의 값들을 consume하기 위해 쓰입니다.

함수형 컴포넌트가 prop drilling을 피하면서 컨텍스트에서 제공된 값에 접근 할 수 있도록 만듭니다.

  1. Create a context
// createContext.js
import React from 'react';

// Create a new context
const MyContext = React.createContext();

export default MyContext;
  1. Provide a value using Context Provider
import React from 'react';
import MyContext from './createContext';

function App() {
  const value = 'Hello, Context!';

  return (
    <MyContext.Provider value={value}>
      <ChildComponent />
    </MyContext.Provider>
  );
}
  1. Consume the context value using ‘useContext’
import React, { useContext } from 'react';
import MyContext from './createContext';

function ChildComponent() {
  const contextValue = useContext(MyContext);

  return <div>{contextValue}</div>;
}

4. Ref Hooks

useRef

value나 DOM 엘리먼트등을 mutable reference로 만들 수 있는 방법을 제공하며 매 렌더때마다 값이 유지됩니다. DOM elements들에게 접근하거나 조작하기 위해 종종 사용됩니다.

import React, { useRef } from 'react';

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

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

  return (
    <div>
      <input type="text" ref={inputRef} />
      <button onClick={handleClick}>Focus Input</button>
    </div>
  );
}

export default Example;

5. Callback Hooks

useCallback

콜백 함수를 메모아이즈합니다. 만약 의존성을 가진 값들이 바뀌지 않은 상태로 유지된다면, 매 렌더시마다 재생성됨을 막습니다. 자식 컴포넌트들의 불필요한 re-render를 하지 않게 하여 성능 최적화에 유용합니다.

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

  const increment = useCallback(() => {
    setCount(count + 1);
  }, [count]);

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

export default Example;

useMemo

value(값)을 메모아이즈 합니다.

매 렌더시마다 의존성 값이 변하지 않는다면 새롭게 계산되는 것을 막습니다.

비용이 많이드는 계산을 최적화 하거나 복잡한 데이터 변형을 할때 성능 최적화에 유용합니다.

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

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

  const doubleCount = useMemo(() => {
    return count * 2;
  }, [count]);

  return (
    <div>
      <p>Count: {count}</p>
      <p>Double Count: {doubleCount}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

export default Example;

6. LayoutEffects

  • useDimensions: 엘리먼트의 dimension을 계산해줍니다.
  • useWindowSize: 현재 윈도의 크기를 반환합니다.

7. Form Hooks

  • useForm: form 상태와 validation helper들을 제공합니다.

8. Animation Hooks

  • useSprings: Creates animated values for animation using React Spring.

9. Custom Hooks

  • You can create your own custom hooks to encapsulate reusable logic and stateful behavior. Custom hooks should follow the naming convention of starting with “use” to ensure they can leverage other hooks.
← Go home