
1. useMemo()
useMemo(() => value, deps), useMemo(fn, deps)
const memoizedValue = useMemo(()=>computedExpensiveValue(a,b),[a,b])
- ๋๋๋ง ๋ ๋๋ง๋ค ๊ฐ์ ๊ณ์ ๊ณ์ฐํ์ง ์๊ณ , ์ด์ ์ ๊ณ์ฐ๋ ๊ฐ์ ๋ฉ๋ชจ์ด์ ์ด์ ํ์ฌ ๋ถํ์ํ ์ฐ์ฐ์ ์ค์ธ๋ค.
- ์๋กญ๊ฒ ๊ณ์ฐํ๋ ๊ธฐ์ค์ ๋๋ฒ์งธ ์ธ์, dependency์ ์ ๋๋ค.
import { useMemo, useState } from 'react';
const App = () => {
console.log('๋ฆฌ๋๋๋ง');
const [isOn, setIsOn] = useState(false);
const [users, setUsers] = useState([
{ active: true },
{ active: true },
{ active: false },
]);
const countActiveUser = () => {
console.log('์ฌ์ฉ์ ์ ์ธ๋์ค...');
return users.filter((user) => user.active).length;
};
const count = useMemo(countActiveUser, [users]);
return (
<div>
<h1>{`ํ์ฑ ์ฌ์ฉ์ ์: ${count}`}</h1>
<button onClick={() => setIsOn((isOn) => !isOn)}>๋ฆฌ๋๋๋ง ํ๊ธฐ</button>
<button
onClick={() => {
setUsers(Array.from(users).concat({ active: true }));
}}
>
์ฌ์ฉ์ ์ถ๊ฐํ๊ธฐ
</button>
</div>
);
};
2. useCallback()
useMemo(() => fn, deps) ์ useCallback(fn, deps) ๋ ๊ฐ๋ค.
- ์ปดํฌ๋ํธ๊ฐ ๋ฆฌ๋ ๋๋ง๋ ๋ ๋ถํ์ํ๊ฒ ํจ์๊ฐ ๋ค์ ์์ฑ๋๋ ๊ฒ์ ๋ฐฉ์งํ๋ค.
- ํจ์ ์์ฑ ์์ฒด๊ฐ ์ค๋ ๊ฑธ๋ฆฌ๋ ๊ฒฝ์ฐ, ํจ์๋ฅผ ์์ ์ปดํฌ๋ํธ์ props๋ก ๋๊ฒจ์ค ๋ useCallback()์ ์ฌ์ฉํ๋ ๊ฒ์ด ์ข๋ค.
import { useState, useCallback } from 'react';
const App = () => {
const [firstName, setFirstName] = useState('junha');
const [lastName, setLastName] = useState('kim');
// ์ด๋ฆ๊ณผ ์ฑ์ด ๋ฐ๋ ๋๋ง๋ค ํ๋ค์์ ๋ฉ๋ชจ์ด์ ์ด์
const getfullName = useCallback(() => {
return `${firstName} ${lastName}`;
}, [firstName, lastName]);
return (
<>
{getfullName()}
<button onClick={() => setFirstName('์คํ')}>๋ฒํผ</button>
</>
);
};
export default App;
3. useRef()
- DOM Element์ ์ ๊ทผ ํ ๋ ์ฌ์ฉํ๋ฉฐ, getElementById()์ ๊ฐ์ ๊ธฐ๋ฅ์ ํ๋ค.
- DOM Element์ ref ์์ฑ์ ์ด์ฉํ๋ค.
import { useRef } from 'react';
const App = () => {
const inputRef = useRef(null);
const focusHandler = () => {
inputRef.current.focus();
};
const clickHandler = () => {
inputRef.current.value += '๊ฐ์ด ๋ฐ๊ผ์ด์ฉ';
};
return (
<div>
<input ref={inputRef} type='text' />
<button onClick={clickHandler}>๊ฐ ๋ฐ๊พธ๊ธฐ</button>
<button onClick={focusHandler}>input์ผ๋ก ํฌ์ปค์ค</button>
</div>
);
};
export default App;
useRef์ ๋ฆฌํด ๊ฐ
- useRef์ ๋ฆฌํด๊ฐ์ current ์์ฑ์ ์ด์ฉํ์ฌ DOM์ ์ปจํธ๋กค ํ ์ ์๋ค.
- ์ด ๊ฐ์ ์ปดํฌ๋ํธ ์์ ์ฃผ๊ธฐ ๋ด์์ ์ ์งํ๋ค.
- useRef ๊ฐ์ฒด๊ฐ ๋ณ๊ฒฝ๋์ด๋ ์ปดํฌ๋ํธ๊ฐ ์ฌ๋ ๋๋ง๋์ง ์๋๋ค.

4. useTitle
: title ํ๊ทธ๋ฅผ ์ ๋ฐ์ดํธํ๋ ๊ธฐ๋ฅ
import { useEffect, useState } from "react";
const useTitle = (initialTitle) => {
const [title, setTitle] = useState(initialTitle);
const updateTitle = () => {
const htmlTitle = document.querySelector("title");
htmlTitle.innerText = title;
};
useEffect(updateTitle, [title]);
return setTitle;
};
const App = () => {
const titleUpdater = useTitle("Loading...");
setTimeout(() => titleUpdater("home"), 3000);
return <div>Hi</div>;
};
export default App;
5. useClick
: ํด๋น element๋ฅผ ํด๋ฆญ ์ ์ฃผ์ด์ง callBackํจ์ ์ถ๋ ฅํ๊ธฐ
: useRef() ์ฌ์ฉ
import { useEffect, useState, useRef } from "react";
const useClick = (onClick) => {
const element = useRef();
useEffect(() => {
if (element.current) {
element.current.addEventListener("click", onClick);
}
return () => {
element.current.removeEventListener("click", onClick);
};
});
return element;
};
const App = () => {
const sayHello = () => console.log("๊ทธ๊ฑธ ๋๋ฅด๋");
const title = useClick(sayHello);
return (
<div className="APP">
<h1 ref={title}>Click me</h1>
</div>
);
};
export default App;
6. useConfirm
: ๋ฉ์ธ์ง๋ฅผ ํ์ธ์์ผ์ฃผ๊ณ , ์๋ต์ ๋ฐ๋ผ ์ฝ๋ฐฑํจ์๋ฅผ ํธ์ถํด์ฃผ๋ ๊ธฐ๋ฅ
: ์ฌ์ฉ์๊ฐ ๋ฒํผํด๋ฆญ ์์
์ ๋ฉ์ธ์ง ๋ณด์ฌ์ฃผ๊ณ ์ถ์ ๋
const useConfirm = (message = "", callback, rejection) => {
if (!callback || typeof callback !== "function") {
return;
}
const confirmAction = () => {
if (confirm(message)) {
callback();
} else {
rejection();
}
};
return confirmAction;
};
const App = () => {
const deleteWorld = () => console.log("Deleting the World");
const abort = () => console.log("Aborted");
const confirmDelete = useConfirm(
"Are you sure to delete the World?",
deleteWorld,
abort
);
return (
<div className="APP">
<button onClick={confirmDelete}>Delete the World</button>
</div>
);
};
export default App;
7. usePreventLeave
: ๋ฒํผ์ ๋ฐ๋ผ ์ด๋ฒคํธ๋ฆฌ์ค๋๋ฅผ ์ถ๊ฐ์์ผ์ฃผ๋ ๊ธฐ๋ฅ
const usePreventLeave = () => {
const listener = (event) => {
event.preventDefault();
event.returnValue = "";
};
const enablePrevent = () => window.addEventListener("beforeunload", listener);
const disablePrevent = () =>
window.removeEventListener("beforeunload", listener);
return { enablePrevent, disablePrevent };
};
const App = () => {
const { enablePrevent, disablePrevent } = usePreventLeave();
return (
<div className="APP">
<button onClick={enablePrevent}>Protect</button>
<button onClick={disablePrevent}>Unprotect</button>
</div>
);
};
export default App;
beforeunload
: allows you to execute a function before the window gets closed, or before the person leaves your page
8. useBeforeLeave
: ๋ง์ฐ์ค๊ฐ ํ์ด์ง๋ฅผ ๋ฒ์ด๋๋ฉด ์คํ์ํค๋ ๊ธฐ๋ฅ
Cleanup Function
useEffect์์ returnํ ํจ์๋ componentWillUnmount ๋ ํธ์ถ๋๋ค.
์ด๋ฒคํธ๋ฆฌ์ค๋๊ฐ ํธ์ถ๋๊ฑฐ๋ ์ ๋ฐ์ดํธ๋ ๋๋ง๋ค ์ด๋ฒคํธ๋ฆฌ์ค๋๊ฐ add๋๋๊ฑธ ์ํ๋๊ฒ ์๋๋ค. ๊ณ ๋ก dependency๋ []๋ก didmount๋ ๋ํ๋ฒ๋ง ํธ์ถํ๊ณ , willunmount๋ ๋ ํด๋ฆฐ์ ํจ์๋ก ๋ฆฌํด ํจ์๋ก ์จ์ฃผ์
import { useEffect } from "react";
const useBeforeLeave = (onBefore) => {
if (typeof onBefore !== "function") {
return;
}
const handle = (event) => {
const { clientY } = event;
if (clientY <= 0) {
onBefore();
}
};
useEffect(() => {
document.addEventListener("mouseleave", handle);
return () => document.removeEventListener("mouseleave", handle);
}, []);
};
const App = () => {
const sayHello = () => console.log("๋ ๋์ง๋ง์ฉ");
useBeforeLeave(sayHello);
return (
<div className="APP">
<h1>Hello</h1>
</div>
);
};
export default App;
9. useFadein
component์ reference๋ฅผ ์ป๋ ๋ฐฉ๋ฒ์ด ํน์ดํ๋ค.
useXXXํจ์์ useRef()๋ฅผ ์ค์ ํ๊ณ ๋ค์ element returnํ๋ ๋ฐฉ์์ผ๋ก ํด๋น element๋ฅผ ์กฐ์ํ๋ค. ์ด ๋ฐฉ๋ฒ์ด ํจ์จ์ ์ธ ์ด์ ๋ ๋ญ๊น? : ์๋ฅผ๋ค์ด fadeinํจ๊ณผ๋ฅผ ์ฃผ๊ธฐ ์ํด์, const el = useFadeIn()์ ์ผ๋ค๊ณ ํด๋ณด์. ๊ทธ๋ผ fadeinํจ๊ณผ๋ฅผ ์ฃผ๊ณ ์ถ์ ํ๊ทธ์ ref={el}๋ง ๋ฃ์ผ๋ฉด ๋ฐ๋ก ๊ทธ element๋ฅผ ์กฐ์ํ ์ ์๋ค. ํ๋ ์์๋ฌ์ผํ ๊ฒ์ html์์๋ฅผ ์กฐ์ํ๊ธฐ ์ํด js๋ถ๋ถ์ ํจ์๋ก ๋ชจ๋ํ์ํค๊ณ , ์ ์ฉํ ๋๋ htmlํ๊ทธ์ ๋ฏธ๋ฆฌ ์ ์ธํด๋ ๋ณ์์ด๋ฆ๋ง prop์ ๋ฃ์ผ๋ฉด ๋๋ค๋ ๊ฒ. ์ด ๋์์ธํจํด์ด ํจ์จ์ ์ผ๋ก ๋ณด์ด๊ธดํ๋ค. ์๋๋ฉด vanilia js์์ ์๋์ํฌ ๋๋ ์ ํด์ง ๊ท๊ฒฉ์ด ์์ด์ ์ฐ๋ฐ์ ์ผ๋ก ์จ์ ธ์์๊ธฐ ๋๋ฌธ์ด๋ค.
import { useEffect, useRef } from "react";
const useFadeIn = (duration = "1") => {
const element = useRef();
useEffect(() => {
if (element.current) {
const { current } = element;
current.style.transition = `opacity ${duration}s`;
current.style.opacity = 1;
}
}, []);
return { ref: element, style: { opacity: 0 } };
};
const App = () => {
const fadeIn3s = useFadeIn(2);
const fadeIn7s = useFadeIn(7);
return (
<div className="APP">
<h1 {...fadeIn3s}>Hello</h1>
<h5 {...fadeIn7s}>MR. JUNHA</h5>
</div>
);
};
export default App;
10. useNetwork
import { useEffect, useState } from "react";
const useNetwork = (onChange) => {
const [status, setStatus] = useState(navigator.onLine);
const handleChange = () => {
setStatus(navigator.onLine);
onChange(navigator.onLine);
};
useEffect(() => {
window.addEventListener("online", handleChange);
window.addEventListener("offline", handleChange);
() => {
window.removeEventListener("online", handleChange);
window.removeEventListener("offline", handleChange);
};
}, []);
return status;
};
const App = () => {
const handleNetworkChange = (onLine) => {
console.log(onLine ? "Online" : "Offline");
};
const onLine = useNetwork(handleNetworkChange);
return (
<div className="APP">
<h1>{onLine ? "Online" : "Offline"}</h1>
</div>
);
};
export default App;
navigator.onLine
- Tells you true or false if your website is online
It's always good to think "maybe people wouldn't just do this" when you're making a library for other people
11. useNotification
import { useEffect, useState, useRef } 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("Enter Summoner", {
body: "Explore the World that you dream"
});
return (
<div className="APP">
<button onClick={triggerNotif}>Hello</button>
</div>
);
};
export default App;
12. useAxios
: about httpRequest
import React from "react";
import useAxios from "./useAxios";
const App = () => {
const { loading, data, error, refetch } = useAxios({
url: "https://yts.mx/api/v2/list_movies.json"
});
console.log(
`Loading: ${loading}\nError:${error}\nData:${JSON.stringify(data)}`
);
return (
<div>
<h1>{data && data.status}</h1>
<h2>{loading && "Loading"}</h2>
<button onClick={refetch}>Refetch</button>
</div>
);
};
export default App;
import defaultAxios from "axios";
import { useState, useEffect } from "react";
const useAxios = (options, axiosInstance = defaultAxios) => {
const [state, setState] = useState({
loading: true,
error: null,
data: null
});
const [trigger, setTrigger] = useState(0);
if (!options.url) {
return;
}
const refetch = () => {
setState({
...state,
loading: true
});
setTrigger(Date.now());
};
useEffect(() => {
axiosInstance(options)
.then((data) => {
setState({
...state,
loading: false,
data
});
})
.catch((error) => {
setState({
...state,
loading: false,
error
});
});
}, [trigger]);
return { ...state, refetch };
};
export default useAxios;
More about Hooks
- https://ko.reactjs.org/docs/hooks-reference.html
- useContext โญ
- useReducer โญ
- useCallback โญ
- useMemo โญ
- useImperativeHandle
- useLayoutEffect
- useDebugValue
More about
https://sangcho.tistory.com/entry/ReactHooks%EC%9D%98%EB%B9%99%EC%82%B0
React Hooks์ ์ปค๋ค๋ ๋น์ฐ
* ์ด ๊ธ์ Iceberg of React Hooks ๋ฒ์ญํ์์ต๋๋ค. The Iceberg of React Hooks React Hooks, unlike Class Components, provide low-level building blocks for optimizing and composing applications with m..
sangcho.tistory.com
'๐ Front > โ๏ธ React JS' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| [JSX]: JS์ JSX ํ์ฅ์๋ ๋ฌด์์ด ๋ค๋ฅผ๊น? (0) | 2021.09.07 |
|---|---|
| [styled-components] ํ์ ์คํฌ๋ฆฝํธ์์ ์ฌ์ฉํ๊ธฐ (0) | 2021.09.02 |
| [React Hook ์๋ฆฌ์ฆ 2]: useEffect() (0) | 2021.07.22 |
| [React Hook ์๋ฆฌ์ฆ 1]: ์ฐ๋ ์ด์ , useState() (0) | 2021.07.20 |
| [React Router] ๋ผ์ฐํฐ ์ฌ์ฉํ๊ธฐ(react-router-dom v5) (0) | 2021.07.20 |