리액트 hooks

hooks>>리액트 버전이 올라가며 새롭게 나온 기능으로

요즘은 대부분 hook을 이용하여 구현

Hook이란

리액트의 Hook은 함수형 컴포넌트에서도 상태와 라이프사이클 기능을 사용할 수 있도록 해주는 기능입니다. Hook은 React 16.8에서 도입되었으며, 가장 일반적으로 사용되는 Hook에는 useState, useEffect, useContext, useReducer, useCallback, useMemo, useRef, useImperativeHandle, useLayoutEffect, useDebugValue 등이 있습니다. 각 Hook의 역할과 사용 예제를 소개하겠습니다.

useState

useState는 함수형 컴포넌트에서 상태를 관리하기 위해 사용됩니다. 상태 변수와 상태를 갱신하는 함수를 반환합니다.

jsx코드 복사
import React, { useState } from 'react';

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

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

useEffect

useEffect는 함수형 컴포넌트에서 사이드 이펙트를 수행하기 위해 사용됩니다. 마운트, 업데이트, 언마운트 시 특정 작업을 수행할 수 있습니다.

jsx코드 복사
import React, { useEffect } from 'react';

const Timer = () => {
  useEffect(() => {
    const timer = setInterval(() => {
      console.log('Tick');
    }, 1000);

    return () => clearInterval(timer); // Cleanup
  }, []);

  return <div>Check the console for timer ticks</div>;
};

useContext

useContext는 Context API를 사용하여 전역 상태를 쉽게 관리할 수 있게 합니다.

jsx코드 복사
import React, { useContext } from 'react';

const MyContext = React.createContext();

const MyComponent = () => {
  const value = useContext(MyContext);
  return <div>{value}</div>;
};

const App = () => (
  <MyContext.Provider value="Hello, World!">
    <MyComponent />
  </MyContext.Provider>
);

useReducer

useReducer는 상태 로직이 복잡한 경우에 useState 대신 사용할 수 있는 Hook입니다. 리듀서 패턴을 사용하여 상태를 관리합니다.

jsx코드 복사
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();
  }
}

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

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

useCallback

useCallback은 메모이제이션된 콜백을 반환합니다. 컴포넌트가 리렌더링될 때 동일한 콜백 함수를 사용하도록 합니다.

jsx코드 복사
import React, { useCallback, useState } from 'react';

const Child = React.memo(({ onClick }) => {
  console.log('Child rendered');
  return <button onClick={onClick}>Click me</button>;
});

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

  const handleClick = useCallback(() => {
    console.log('Button clicked');
  }, []);

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