λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°

FA/React

20221105 React Hooks - Custom Hooks μ»€μŠ€ν…€ ν›…

Hook의 κ·œμΉ™

  • React ν•¨μˆ˜ ꡬ성 μš”μ†Œ λ‚΄μ—μ„œλ§Œ ν˜ΈμΆœν•  수 있음(λ°˜λ“œμ‹œ Functional Component μ•ˆμ—μ„œ μ‚¬μš©ν•΄μ•Ό 함)
  • ꡬ성 μš”μ†Œμ˜ μ΅œμƒμœ„μ—μ„œλ§Œ ν˜ΈμΆœν•  수 있음
  • 쑰건문, 반볡문 μ•ˆμ—μ„œ λͺ» 씀

Custom Hook

- 두 개의 μžλ°”μŠ€ν¬λ¦½νŠΈ ν•¨μˆ˜μ—μ„œ 같은 λ‘œμ§μ„ κ³΅μœ ν•˜κ³ μž ν•  λ•ŒλŠ” 또 λ‹€λ₯Έ ν•¨μˆ˜λ‘œ 뢄리 함.

- μ€‘λ³΅λœ μ½”λ“œλ₯Ό λ°œκ²¬ν•˜λ©΄ μž¬μ‚¬μš©μ΄ κ°€λŠ₯ν•œ ν•¨μˆ˜λ‘œ λ§Œλ“€μ–΄μ„œ 쀑볡을 μ œκ±°ν•  수 있음.

- μ»€μŠ€ν…€ ν›… λ‚΄λΆ€μ—μ„œ λ‹€λ₯Έ 훅듀을 자유둭게 μ‘°ν•©κ°€λŠ₯(ν•„μš”ν•œ μΈν„°νŽ˜μ΄μŠ€μ™€ κΈ°λŠ₯ μΆ”κ°€ κ°€λŠ₯)

- μ»€μŠ€ν…€ν›… λ‚΄λΆ€μ—μ„œ μ»€μŠ€ν…€ 훅이 κ°€μ§€λŠ” μŠ€ν…Œμ΄νŠΈμ™€ μ΄νŽ™νŠΈλŠ”  μ™„μ „νžˆ 독립적이기 λ•Œλ¬Έμ— μž¬μ‚¬μš©μ΄ μ•„μ£Ό μ’‹μŒ

use0000 처럼 λ°˜λ“œμ‹œ 맨 μ•žμ— useλΌλŠ” 단어λ₯Ό λΆ™μ—¬μ„œ λ‹€λ₯Έ κ°œλ°œμžλ“€μ΄ Hookμ΄λΌλŠ” κ±Έ μ•Œ 수 있게 ν•΄μ€˜μ•Ό 함.

 

μ»€μŠ€ν…€ ν›… μ˜ˆμ‹œ

1. useAsync

비동기 ν•¨μˆ˜μ˜ λ‘œλ”©, μ—λŸ¬ 처리λ₯Ό ν•˜λŠ” 데 μ‚¬μš©ν•  수 μžˆλŠ” ν•¨μˆ˜

function useAsync(asyncFunction) {
  const [pending, setPending] = useState(false);
  const [error, setError] = useState(null);

  const wrappedFunction = useCallback(async (...args) => {
    setPending(true);
    setError(null);
    try {
      return await asyncFunction(...args);
    } catch (error) {
      setError(error);
    } finally {
      setPending(false);
    }
  }, [asyncFunction]);

  return [pending, error, wrappedFunction];
}

2.useToggle

toggle ν•¨μˆ˜λ₯Ό ν˜ΈμΆœν•  λ•Œλ§ˆλ‹€ value 값이 μ°Έ/κ±°μ§“μœΌλ‘œ λ²ˆκ°ˆμ•„κ°€λ©° λ°”λ€œ (ON/OFF μŠ€μœ„μΉ˜ 등에 μ‚¬μš©)

function useToggle(initialValue = false) {
  const [value, setValue] = useState(initialValue);
  const toggle = () => setValue((prevValue) => !prevValue);
  return [value, toggle];
}

 

 

 

참고자료 및 좜처

https://github.com/streamich/react-use

 

GitHub - streamich/react-use: React Hooks — πŸ‘

React Hooks — πŸ‘. Contribute to streamich/react-use development by creating an account on GitHub.

github.com

https://ko.reactjs.org/docs/hooks-custom.html

 

μžμ‹ λ§Œμ˜ Hook λ§Œλ“€κΈ° – React

A JavaScript library for building user interfaces

ko.reactjs.org

https://www.w3schools.com/react/react_customhooks.asp

 

React Custom Hooks

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

μ½”λ“œμž‡ - React둜 데이터 닀루기 κ°•μ˜