[React] Custom Hooks

Seungmin Lee·2022년 9월 29일
0

React

목록 보기
8/9
post-thumbnail

fetch로 데이터를 받아오거나, input에 의한 상태 변경과 같은 로직은 자주 사용되고 여러 컴포넌트에서 사용된다. 이럴 때 Custom Hooks를 사용하면 매번 같은 코드를 반복해서 작성할 필요 없이 만들어둔 Custom Hook을 불러와 편리하게 사용할 수 있다.

🌼 Custom Hooks의 핵심 개념

  • Custom Hook의 이름은 use로 시작해야 한다. (ex. useInput)
  • Custom Hook 안에서 모든 React 내장 Hook을 쓸 수 있다.
  • 같은 Custom Hook을 여러 곳에 사용하더라도, 같은 state를 공유하지 않고 독립적으로 작동한다.

// App.js
import { useState } from 'react';

function App(){
  const [inputValue, setInputValue] = useState('');
  
  const handleChange = (e) => {
    setInputValue(e.target.value);
  };
  
  const handleSubmit = () => {
    alert(inputValue);
    setInputValue('');
  };  
  
  
  return (
  	<div>
    	<h1>useInput</h1>
    	<input value={inputValue} onChange={handleChange} />
      <button onClick={handleSubmit}>확인</button>
    </div>
  )
}

위의 코드에서 자주 사용되는 로직을 아래의 코드처럼 Custom Hook으로 분리할 수 있다. Custom Hook의 이름은 useInput으로 하고 useInput.js파일로 따로 빼서 작성하였다.

// useInput.js
import { useState } from 'react';

export function useInput(initalValue, submitAction){
  const [inputValue, setInputValue] = useState(initalValue);
  
  const handleChange = (e) => {
    setInputValue(e.target.value);
  };
  
  const handleSubmit = () => {    
    setInputValue('');
    submitAction(inputValue)
  };  
  
  
  return [inputValue, handleChange, handleSubmit]
}

// App.js
// useInput 불러오기
import { useInput } from './useInput'

// alert 로직은 전역으로 빼줌
function displayMessage(message) {
  alert(message);
}

function App(){
  // useInput이 리턴하는 값들을 구조분해할당을 이용해서 받으면 편리하게 사용할 수 있다.
  const [inputValue, handleChange, handleSubmit] = useInput('', displayMessage)
  
  return (
  	<div>
    	<h1>useInput</h1>
    	<input value={inputValue} onChange={handleChange} />
      <button onClick={handleSubmit}>확인</button>
    </div>
  )
}

Reference)
React Hooks에 취한다 - Custom Hooks 커스텀 훅 | 리액트 훅스 시리즈

profile
<Profile name="seungmin" role="frontendDeveloper" />

0개의 댓글