REACT ⑨ Making a Custom Hook

옛슬·2022년 1월 9일
0

REACT 🔵

목록 보기
9/16
post-thumbnail

🚩 해당 글은 유튜브 The Net Ninja와 React 공식문서를
공부한 토대로 작성된 글입니다. 혹시라도 잘못된 글이 있다면
댓글로 알려주세요 🏃‍♀️🏃‍♀️

Making a Custom Hook

Custom Hook

  • Each call to a Hook gets isolated state
  • 보통 custom hook을 만들 때 use라는 키워드로 시작함.
  • hooks라는 디렉터리를 만들어서 hook을 파일별로 관리함.
  • 결론적으로 컴포넌트 로직을 뽑아내서 정의한 후 간편하게 호출할 수 있음

Example

import { useState, useEffect } from "react";

const useFetch = (url) => {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch(url)
      .then((res) => res.json())
      .then((data) => setData(data));
  }, [url]);

  return data;
};

export default useFetch;

//data.js
import useFetch from "./hooks/useFetch";

const Data = () => {
  const comment = useFetch("https://jsonplaceholder.typicode.com/comments/1");
  const users = useFetch("https://jsonplaceholder.typicode.com/users");

  return (
    <section className="data-section">
      <h2>Data 뿌려주기 연습</h2>
      <h3>코멘트</h3>
      <article className="comment">
        <div className="comment-img">
          <img
            src="..."
            alt="user"
          />
        </div>
        <div className="comment-info">
          <strong>{comment && comment.email}</strong>
          <h4>{comment && comment.name}</h4>
          <p>{comment && comment.body}</p>
        </div>
      </article>
      ...
    </section>
  );
};

export default Data;
  • 너무 길어서 일부분만 가져와봤다. 결론적으로 fetching data에 관련된 로직이 똑같기 때문에 해당 로직을 재사용하기 위해 커스텀 훅을 제작한 후 사용하면 된다.
  • return data 구문을 통해 데이터를 받은 후, comment 혹은 users와 같이 변수에 담아서 해당 데이터를 사용하면 된다!
profile
웹 퍼블리셔입니다💓

0개의 댓글