Custom Hooks

이인재·2022년 10월 17일

React

목록 보기
14/14

Custom Hooks

언제 사용?

주로 Input을 관리할 때, Fetch를 요청할 때 사용한다.

왜 사용?

  1. 코드, 로직의 반복을 최소화.
  2. 재사용성 높임.
  3. 변경사항 있을 때 커스텀 훅에서만 변경하면 되기에 효과적이고 효율적이다.

useFetch

useFetch 사용 전

//App.js
import { useState, useEffect } from 'react';
import axios from 'axios';
import './App.css';

function App() {
  const [quote, setQuote] = useState(null);
  const [loading, setLoading] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    setLoading('loading...')
    setQuote(null);
    setError(null);
    const source = axios.CancelToken.source();
    axios.get('https://api.quotable.io/random', { cancelToken: source.token })
      .then(res => {
      setLoading(false);
      setQuote(res.data.content);
    })
      .catch(err => {
      setLoading(false)
      setError('An error occurred. Awkward..')
    })
    return () => {
      source.cancel();
    }
  }, [])

  return (
    <div className="App">
      <button onClick={fetchQuote}>Fetch Quote</button>
      { loading && <p>{loading}</p> }
      { quote && <p>"{quote}"</p> }
      { error && <p>{error}</p> }
    </div>
  )
}

export default App;

useFetch 사용 후

//useFetch.js
import { useState, useEffect } from 'react';
import axios from 'axios';

function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    setLoading('loading...')
    setData(null);
    setError(null);
    const source = axios.CancelToken.source();
    axios.get(url, { cancelToken: source.token })
      .then(res => {
      setLoading(false);
      res.data.content && setData(res.data.content);
      res.content && setData(res.content);
    })
      .catch(err => {
      setLoading(false)
      setError('An error occurred. Awkward..')
    })
    return () => {
      source.cancel();
    }
  }, [url])

  return { data, loading, error }

  export default useFetch;

useFetch라는 커스텀 훅을 사용했다.

컴포넌트에 useFetch 사용

import useFetch from './useFetch';
import './App.css';

function App() {
const { data: quote, loading, error } = useFetch('https://api.quotable.io/random')

return (
  <div className="App">
    { loading && <p>{loading}</p> }
    { quote && <p>"{quote}"</p> }
    { error && <p>{error}</p> }
  </div>
);
}

export default App;

결론적으로는, useFetch는 안에서 결과, 로딩, 에러 상태를 반환해주는 커스텀 훅이다.

0개의 댓글