Class를 작성할 필요 없이 상태 값과 여러 React기능을 사용할수 있다.
Hook은 함수 컴포넌트에서 React state와 생명주기 기능을 연동할수 있게 해주는 함수이다. Hook은 Class안에서 동작하지 않는다.
1. 최상위 에서만 Hook을 호출해야 한다. 반복문, 조건문, 중첩된 함수 내에서 Hook은 동작하지않는다.
2. React 함수 컴포넌트 내에서만 Hook을 호출한다. 일반 js함수에서는 Hook은 동작하지 않는다.
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;