- Rules of Hooks
- Why custom Hooks?
- Creating Custiom Hooks
- Using Custom Hooks
Rules of Hooks
- Only call Hooks in Component or Other Hook Functions
React Hooks must not be called outside of React component functions - Only call Hooks on the top level
React Hooks must not be called in nested code statements (e.g, inside of if-statements)
Why custom Hooks?
컴포넌트 함수에 들어가는 코드를 감싸고 재사용하기 위함
여러곳에서 사용해야 하는 로직에 대해 함수로 만든 후 재사용
Custom Hooks의 이점:
- 재사용성: Custom Hooks는 컴포넌트 간 로직을 쉽게 공유할 수 있습니다.
- 분리와 추상화: 특정 로직을 Custom Hook으로 분리하여 컴포넌트의 복잡도를 줄일 수 있습니다.
- 독립적인 상태 관리: Custom Hooks를 사용하는 각 컴포넌트는 독립적인 상태를 갖습니다.
즉, 한 컴포넌트의 상태가 변경되어도 다른 컴포넌트의 상태에 영향을 미치지 않습니다.
Creating Custom Hooks
hooks / useCustomHook.jsx
use로 시작해야 hook으로 인식 후, 해당 규칙이 반영됨.
CustomHook 내부에서 관련 상태값들을 관리하고, return
! 다른 컴포넌트에서 사용하더라도, custom hook은 독립적인 상태 스냅샷으로 이용됨!
import { useState, useEffect } from 'react';
// useCustomHook: 사용자 정의 Hook
function useCustomHook(initialValue) {
const [value, setValue] = useState(initialValue);
useEffect(() => {
console.log(`Value has been updated to: ${value}`);
}, [value]);
const resetValue = () => setValue(initialValue);
return [value, setValue, resetValue];
}
export default useCustomHook;
Using Custom Hooks
import React from 'react';
import useCustomHook from './hooks/useCustomHook';
function MyComponent() {
const [count, setCount, resetCount] = useCustomHook(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={resetCount}>Reset</button>
</div>
);
}
export default MyComponent;
Custom Hook 안에 있는 모든 상태와 함수들이 해당 컴포넌트에서 독립적으로 관리