React Hooks

y0ung·2021년 2월 11일
0

React-hooks

목록 보기
1/6
post-thumbnail

Hook?

Class를 작성할 필요 없이 상태 값과 여러 React기능을 사용할수 있다.

Hook은 함수 컴포넌트에서 React state와 생명주기 기능을 연동할수 있게 해주는 함수이다. Hook은 Class안에서 동작하지 않는다.

✌ Hook 사용 규칙

1. 최상위 에서만 Hook을 호출해야 한다. 반복문, 조건문, 중첩된 함수 내에서 Hook은 동작하지않는다.

2. React 함수 컴포넌트 내에서만 Hook을 호출한다. 일반 js함수에서는 Hook은 동작하지 않는다.

📌 기본 Hook

🔌다른 내장 Hook

  • useReducer
  • useCallback
  • useMemo
  • useRef
  • useImperativeHandle
  • useLayoutEffect
  • useDebugValue

💡 나만의 Hook 만들기

useNotification

import React from "react";

const useNotification = (title, options) => {
 if (!("Notification" in window)) return;

 const fireNotif = () => {
   if (Notification.permission !== "granted") {
     Notification.requestPermission().then((permission) => {
       if (permission === "granted") {
         new Notification(title, options);
       } else return;
     });
   } else {
     new Notification(title, options);
   }
 };
 return fireNotif;
};

const App = () => {
 const triggerNotif = useNotification("Can I steal your pizza?", {
   body: "I love Pizza"
 });
 return (
   <div style={{ height: "1000vh" }}>
     <button onClick={triggerNotif}>hello</button>
   </div>
 );
};

export default App;

참고
https://ko.reactjs.org/docs/hooks-overview.html

profile
어제보다는 오늘 더 나은

0개의 댓글