const Hook1 = () => {
const [count, setCount] = useState(1);
const plus = () => setCount(count + 1);
const minus = () => setCount(count - 1);
return (
<>
<div>{count}</div>
<button onClick={plus}>+</button>
<button onClick={minus}>-</button>
</>
);
};
const useInput = (initialState) => {
const [value, setValue] = useState(initialState);
const onChange = (e) => {
console.log(e.target.value);
setValue(e.target.value);
};
return { value, onChange };
};
const Hook2 = () => {
const name = useInput("Mr.");
return (
<>
<div>HI</div>
<input placeholder="" {...name}></input>
</>
);
};
const useInputVaild = (initialState, vaildator) => {
const [value, setValue] = useState(initialState);
const onChange = (e) => {
let willupdate = true;
console.log(e.target.value);
if (typeof vaildator === "function") {
willupdate = vaildator(e.target.value);
}
if (willupdate) {
setValue(e.target.value);
}
};
return { value, onChange };
};
const Hook3 = () => {
const name = useInputVaild("Mr.", (v) => v.length <= 10);
return (
<>
<div>
<input placeholder="" {...name}></input>
</div>
</>
);
};
const AJAXData = [
{
title: "Section-1",
content: "This is Section - 1 Content",
},
{
title: "Section-2",
content: "This is Section - 2 Content",
},
{
title: "Section-3",
content: "This is Section - 3 Content",
},
];
//์
๋ ฅ : ์ด๊ธฐ ํญ์ธ๋ฑ์ค/๋ฐฐ์ด ๋ฐ์ดํฐ : ์ถ๋ ฅ ํ์ฌ ์ฝํ
์ธ ๋ฐ ์ธ๋ฑ์ค ๋ณ๊ฒฝํจ์
const useTabs = (initIdx, arrayData) => {
const [idx, setIdx] = useState(initIdx);
if (!Array.isArray(arrayData)) {
return;
}
return { data: arrayData[idx], setIdx };
};
const Hook4 = () => {
const sectionTab = useTabs(0, AJAXData);
return (
<>
{AJAXData.map((e, i) => (
<button onClick={() => sectionTab.setIdx(i)}>{e.title}</button>
))}
<div>{sectionTab.data.content}</div>
</>
);
};
- useEffect : ๋ฌด์กฐ๊ฑด ์คํ๋๋ ์ฌ์ด๋ ์ดํฉํธ | ํ๋ฒ๋ง ์คํ๋๋ ์ฌ์ด๋ ์ดํํธ | ํน์ ๋ณ์๊ฐ ๋ฐ๋๋ฉด ์คํ๋๋ ์ดํํธ
- ์ฝ๋๋ ์์์ ์๋๋ก ์คํ๋๋ค. | useEffect๊ฐ ์ถ์ ํ๋ ๋ณ์๊ฐ useEffect ์ฝ๋์๋์ ์๋ค๋ฉด ๋ฌด์ฉ์ง๋ฌผ
- ๋๋๋ง ํ์ ํ๋ฒ์ ๋ชจ์๋ค๊ฐ ์คํ๋๋ค.3
useEffect(() => {
console.log("cnt Changed");
});
useEffect(() => {
console.log("cnt Changed");
}, []);
useEffect(() => {
console.log("cnt Changed");
}, [cnt]);
useEffect(() => {
D.addEventLisenter("click", e);
return () => {
D.removeEventLisenter("click", e);
};
}, [D]);
//์ฌ์ด๋ ์ดํํธ๋ก ๋ฌธ์์ title๋ฅผ ๋ณ๊ฒฝํ๋ค.
const useTitle = (initalTitle) => {
const [title, setTitle] = useState(initalTitle);
useEffect(() => {
const htmlTitle = document.querySelector("title");
htmlTitle.innerText = title;
}, [title]);
return setTitle;
};
const Hook6 = () => {
const titleUpdator = useTitle("DOSIMPACT");
setTimeout(() => titleUpdator("BOOM!!"), 3000);
return <></>;
};
- useRef ๋ getElementByIdํด์ ๊ฐ์ ธ์จ ํ๊ทธํธ๋ค๋ฌ์ ๋น์ทํ๋ค.
const Hook7 = () => {
const nameInputRef = useRef();
setTimeout(() => nameInputRef.current && nameInputRef.current.focus(), 1000);
return (
<div>
<input ref={nameInputRef} placeholder="name"></input>
</div>
);
};
//ํน์ HTML ์ > ํด๋ฆญ์ ํธ๋ฆฌ๊ฑฐ๋ก > ํน์ ํจ์ ์คํ
const useClick = (onClick) => {
const element = useRef();
useEffect(() => {
const HTMLHandler = element.current;
if (HTMLHandler) {
HTMLHandler.addEventListener("click", onClick);
}
return () => {
HTMLHandler.removeEventListener("click", onClick);
};
}, [onClick]);
return element;
};
const Hook8 = () => {
const sayHello = () => console.log("helllo");
const title = useClick(sayHello);
return (
<div>
<h2 ref={title}>TITLE</h2>
</div>
);
};
- useConfirm, ํน์ ํจ์ ์์์ ์ ํ์ธ ๋ฐ๊ธฐ
//ํน์ ํจ์๋ฅผ ์คํํ๊ธฐ ์ ์, ํ์ธ ๋ฉ์์ง๋ฅผ ๋์ง๊ธฐ
const useConfirm = (message, onConfirm, onCancel) => {
if (!onConfirm || typeof onConfirm !== "function") {
return;
}
if (onCancel && typeof onCancel !== "function") {
return;
}
const confirmAction = () => {
if (window.confirm("message")) {
onConfirm();
} else {
onCancel();
}
};
return confirmAction;
};
const Hook9 = () => {
const deleteWorldConfirm = () => console.log("DELETE WORLD Suc");
const deleteWorldDelete = () => console.log("DELETE WORLD Fail");
const confirmDelete = useConfirm(
"Sure? ",
deleteWorldConfirm,
deleteWorldDelete
);
return (
<div>
<button onClick={confirmDelete}>DELETE</button>
</div>
);
};
- ์ฐฝ ๋ซ๊ธฐ์ ์ ํ์ธ
const usePreventLeave = () => {
const listener = (e) => {
e.preventDefault();
e.returnValue = "";
};
const enablePrevent = () => window.addEventListener("beforeunload", listener);
const disablePrevent = () =>
window.removeEventListener("beforeunload", listener);
return { enablePrevent, disablePrevent };
};
const Hook10 = () => {
const { enablePrevent, disablePrevent } = usePreventLeave();
return (
<>
<div>
<button onClick={enablePrevent}>Protect</button>
<button onClick={disablePrevent}>unProtect</button>
</div>
</>
);
};
const useBeforeLeave = (onBefore) => {
// if (typeof onBefore !== "function") {
// return;
// }
useEffect(() => {
const handle = () => {
onBefore();
};
document.addEventListener("mouseleave", handle);
return () => document.removeEventListener("mouseleave", handle);
}, [onBefore]);
};
const Hook11 = () => {
const beggingYou = () => console.log("please dont leave me..");
useBeforeLeave(beggingYou);
return <div>BEGGING</div>;
};
- useFadeIn
const useFadeIn = () => {
const element = useRef();
useEffect(() => {
if (element.current) {
const { current } = element;
current.style.transition = `opacity 3s`;
current.style.opacity = 1;
}
}, []);
return { ref: element, style: { opacity: 0 } };
};
const Hook12 = () => {
const titleFadein = useFadeIn();
return (
<>
<h2 {...titleFadein}>DOS-IMPACT</h2>
</>
);
};
// ๋จ์ํ๊ฒ ํ์ฌ์ ์คํฌ๋กค ์์น๋ฅผ ๋ฐํํด ์ค๋ค.
const useScroll = () => {
const [state, setState] = useState({
x: 0,
y: 0,
});
const onScroll = () => {
setState({ y: window.scrollY, x: window.scrollX });
};
useEffect(() => {
window.addEventListener("scroll", onScroll);
return () => window.removeEventListener("scroll", onScroll);
}, []);
return state;
};
const Hook14 = () => {
const position = useScroll();
return <>{JSON.stringify(position)}</>;
};
https://reactjs.org/docs/hooks-faq.html#how-can-i-do-data-fetching-with-hooks
- ํ ๊ท์น ๋ณผ๊ฒ!!
-
useEffect์ ๋๋๋ง ์ฌ์ดํด ์ดํด ์์ง X
-
try ์์ data๋ฅผ ๊ฐ์ ธ์ค๊ณ , setState๋ก data๋ฅผ ์ ์ฅํ๋ ์๊ฐ, useEffect ๊ตฌ๋ฌธ์์ ๋น๋๊ธฐ์ ์ผ๋ก ๋๋๋ง์ด ๋จ ( data๊ฐ ์ ๋ค์ด์ด )
-
finally ์์ loading์ false๋ก ๋ฐ๊พธ๋ ์๊ฐ, ์๋ data๊ฐ ์๋ ์ด๊ธฐ์ํ์ state์ loading๋ง false๋ก ๋๋๋ง์ด ํ๋ฒ ๋ ๋๋๋ฏ.
-
๋ฌธ์ ์ ์ฝ๋
const useAxios = (opts, axiosInstance = defaultAxios) => {
const [state, setState] = useState({
loading: true,
erorr: false,
data: null,
});
const [trigger, setTrigger] = useState(false);
const triggerRefectch = () => {
setTrigger(!trigger);
setState({ ...state, loading: true });
};
useEffect(async () => {
try {
const { data } = await axiosInstance(opts);
console.log("useEFFECT try : ");
console.log(state);
console.log(data);
setState({ ...state, data });
} catch (error) {
setState({ error: true });
} finally {
//setState({ loading: false });
console.log("useEFFECT finally : ");
console.log(state);
}
}, []);
return { ...state, triggerRefectch };
};
- ๋์ฝ์ค ์ฝ๋
const useAxios = (opts, axiosInstance = defaultAxios) => {
const [state, setState] = useState({
loading: true,
erorr: false,
data: null,
});
const [trigger, setTrigger] = useState(false);
const triggerRefectch = () => {
setTrigger(!trigger);
setState({ ...state, loading: true });
};
useEffect(async () => {
axiosInstance(opts)
.then((data) => {
setState({
...state,
loading: false,
data,
});
})
.catch((error) => {
setState({ ...state, loading: false, error });
});
}, []);
return { ...state, triggerRefectch };
};
- try React Helmet component like ~~
-
์ ์ ์ ํ๋กํ,์ด๋ฉ์ผ ์ ๋ณด๊ฐ ํ์ํด, ๋ฉ์ธํ๋ฉด,์์ธํ๋ฉด ๋ฑ > ๋งค๋ฒ API์ ํธ์ถํ ์๋ ์๋ค.
-
์์ฒญํฐ ์ปดํฌ๋ํธ(๋ชจ๋๋ฅผ ๊ฐ์ธ๋)๋ฅผ ๋ง๋ค๊ณ , ํ์ ๋ผ์ฐํ ์ ๋ง๋ ๋ค. ์ ๋ณด๋ฅผ ๊ฐ์ ธ์ค๊ธฐ๋ง ํ๋ฉด ์๊ด์๋ค.
-
ํ์ง๋ง, ์ ๋ณด๋ฅผ ์์ ํ๋ค๋ฉด, ๋ฌธ์ ๊ฐ ๋ฐ์ํ๋ค. ์์ ์ปดํฌ๋ํธ๋ ์ ์ ์ปค์ง๊ณ , Redux์ ํ์์ฑ์ด ์๊ธด๋ค.
-
๋ง์ฝ, ์ปดํฌ๋ํธ๊ฐ ๋ง์์ง๋ค๊ณ ์๊ฐํด๋ด๋ผ. ํค๋์ ์ ์ ์ ์ ๋ณด๊ฐ ์๋ค๋ฉด >
-
๋ฐ์ดํฐ ๊ฐ์ ธ์ค๋ ์ปดํฌ๋ํธ > ํค๋ ์ปดํฌ๋ํธ > ์ ์ ์ ๋ณด ์ปดํฌ๋ํธ ... : ๋ฑ์ ์์๋ก ์จ๋ค๋ฉด
-
์ ์ ์ ๋ณด ์ปดํฌ๋ํธ๋ก props๋ฅผ ๋ณด๋ด๊ธฐ์ํด ๋ค๋ฅธ ์ปดํฌ๋ํธ๊ฐ ์ฐ์ง๋ ์์ ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ง๊ณ ์๋๊ฑด ๋ญ๋น๋ค.
-
๋ฐ์ดํฐ ํ์ฐ์ค๋ฅผ ํ๋ ๋ง๋ค์ด์, ์ ์ ์ด๋ฉ์ผ, ์ ์ ํ๋กํ์ ์ ์ฅํด๋
-
ํน์ ์ปดํฌ๋ํธ๊ฐ ํด๋น ๋ฐ์ดํฐ๊ฐ ํ์ํ ๋๋ง๋ค ๊ฐ์ ธ์ค๋ฉด ํด๊ฒฐ๋์ง.
-
์ด๋ฐ ์ ์ฅ์๋ ๋ฆฌ๋์ค,๋ชธ์์ค,UseContext ๊ฐ ๋ ์ ์๋ค. ( ์ฌ๋ฌ๊ฐ์ง ๋ฐฉ๋ฒ์ด ์์ด.)
-
UseContext๋ ๋ณด๋ค ์ฌํํ ์ํ๊ด๋ฆฌ์์ ํ์ํ ํ๊ณ
-
Redux๋ ์ข ๋ ์ปค๋ค๋ Statesใน์ ๋ง์ ๋ณํ๋ค์ด ์์๋ ์ ํฉํ๋ค๊ณ ๋ณธ๋ค.
import React, { useState } from "react";
//์ฌ๋ฌ๊ตฐ๋์์ ์ฌ์ฉ์์
//const { user, logUserIn, logUserOut } = useContext(UserContext); ์ด๋ ๊ฒ
export const UserContext = React.createContext();
const UserContextProvider = ({ children }) => {
const [user, setUser] = useState({ name: "Dosimpact", loggedIn: false });
const logUserIn = () => setUser({ ...user, loggedIn: true });
const logUserOut = () => setUser({ ...user, loggedIn: false });
return (
<UserContext.Provider value={{ user, logUserIn, logUserOut }}>
{children}
</UserContext.Provider>
);
};
//ํ๋ฒ๋ง ์์ ์ปดํฌ๋ํธ์์ ์ ์ธ ๋ ์์
export default UserContextProvider;
const Hook18 = () => {
return (
<UserContextProvider>
<Screen />
</UserContextProvider>
);
};
const Screen = () => {
return <Header />;
};
const Header = () => {
const { user, logUserIn, logUserOut } = useContext(UserContext);
return (
<>
<div>Hello {user.name}</div>
<button onClick={logUserIn}>Login</button>
<button onClick={logUserOut}>LogOut</button>
<div>You are in {user.loggedIn ? "Log in " : "Log Out"}</div>
</>
);
};
import React, { useState, useContext } from "react";
//์ฌ๋ฌ๊ตฐ๋์์ ์ฌ์ฉ์์
//const { user, logUserIn, logUserOut } = useContext(UserContext); ์ด๋ ๊ฒ
export const UserContext = React.createContext();
const UserContextProvider = ({ children }) => {
const [user, setUser] = useState({ name: "Dosimpact", loggedIn: false });
const logUserIn = () => setUser({ ...user, loggedIn: true });
const logUserOut = () => setUser({ ...user, loggedIn: false });
return (
<UserContext.Provider value={{ user, Fns: { logUserIn, logUserOut } }}>
{children}
</UserContext.Provider>
);
};
export const useUser = () => {
const { user } = useContext(UserContext);
return user;
};
export const useUserFns = () => {
const { Fns } = useContext(UserContext);
return Fns;
};
//ํ๋ฒ๋ง ์์ ์ปดํฌ๋ํธ์์ ์ ์ธ ๋ ์์
export default UserContextProvider;
import UserContextProvider, {
UserContext,
useUser,
useUserFns,
} from "./context";
const Hook18 = () => {
return (
<UserContextProvider>
<Screen />
</UserContextProvider>
);
};
const Screen = () => {
return <Header />;
};
const Header = () => {
// const { user, logUserIn, logUserOut } = useContext(UserContext);
const userData = useUser();
const userFns = useUserFns();
return (
<>
<div>Hello {userData.name}</div>
<button onClick={userFns.logUserIn}>Login</button>
<button onClick={userFns.logUserOut}>LogOut</button>
<div>You are in {userData.loggedIn ? "Log in " : "Log Out"}</div>
</>
);
};
- ๋ฌธ์ ์์ JS ๋ก์ง์ผ๋ก๋ง ๊ฐ๋ค๋ฉด ๋ฆฌ๋๋๋ง์ด ์๋ค. ( ์ค์ ๋ก ์์น์ ๋ณด ์ ๋ฐ์์์ง๋ง, ํ๋ฉด์ ๊ทธ๋ฆฌ์ง ๋ชปํจ.)
import { useState, useEffect } from "react";
export default () => {
let state = { coords: { lat: null, long: null }, error: null };
const succ = (pos) => {
const { latitude: lat, longitude: long } = pos.coords;
console.log(pos.coords);
state = { ...state, coords: { lat, long } };
};
const error = (err) => {
state = { ...state, error: true };
};
navigator.geolocation.getCurrentPosition(succ, error);
return state;
};
- ์ผ๋ด state๋ฅผ ํตํด, ๋ง๋ค์๋ค. DOM ์ด ๋ฐ๋๋ถ๋ถ๋ง ๋๋๋ง ํ๋ค ํ์ผ๋, ํ์ฌ ์์น๊ฐ ๊ณ ์ ๋ ์ด์, ๋ฌดํ ๋๋๋ง์ด ๋ ๊น? ( ์ค์ > ๋ฌดํ ๋๋๋ง ์ค ...)
import { useState } from "react";
export default () => {
//const [updated, setUpdated] = useState(false);
const [state, setState] = useState({
coords: { lat: null, long: null },
error: null,
});
const succ = (pos) => {
const { latitude: lat, longitude: long } = pos.coords;
setState({ ...state, coords: { lat, long } });
};
const error = (err) => {
setState({ ...state, error: true });
};
const fetchData = () => {
navigator.geolocation.getCurrentPosition(succ, error);
};
fetchData();
return state;
};
- useEffect๋ฅผ ์ฌ์ฉํด์, ๋ฌดํ ๋๋๋ง์ ๋ง์์ง๋ง, Effect ํํ ๊ฑฐ์ง๋ง์ ํ์.
- fetchDtatํจ์๋ ๋งค ๋๋๋ง ๋ง๋ค ๋ฐ๋๋๋ฐ, ์๋ฐ๋๋ค๊ณ ์๊ธฐํจ.
import { useState, useEffect } from "react";
export default () => {
//const [updated, setUpdated] = useState(false);
const [state, setState] = useState({
coords: { lat: null, long: null },
error: null,
});
const succ = (pos) => {
const { latitude: lat, longitude: long } = pos.coords;
setState({ ...state, coords: { lat, long } });
};
const error = (err) => {
setState({ ...state, error: true });
};
const fetchData = () => {
navigator.geolocation.getCurrentPosition(succ, error);
};
//fetchData();
useEffect(() => {
fetchData();
}, []);
return state;
};
- ์์กด์ฑ ์์ ์ ๊ฑฐ
import { useState, useEffect } from "react";
export default () => {
const [state, setState] = useState({
coords: { lat: null, long: null },
error: null,
});
useEffect(() => {
const succ = (pos) => {
const { latitude: lat, longitude: long } = pos.coords;
setState((pre) => ({ ...pre, coords: { lat, long } }));
};
const error = (err) => {
setState((pre) => ({ ...pre, error: true }));
};
navigator.geolocation.getCurrentPosition(succ, error);
}, []);
return state;
};
- ์นด์ดํฐ
//๋ง๋ฒ์ useEffect๊ฐ ์๋๋๋ ํ์...
const Counter = () => {
const [cnt, setCnt] = useState(0);
useEffect(() => {
console.log("Effect is running");
const id = setInterval(() => {
setCnt((c) => {
console.log("COUTER UPDATE", c);
return c + 1;
});
}, 1000);
return () => {
console.log("EFFECT IS CLEARED");
clearInterval(id);
};
}, []);
return <>{cnt}</>;
};
const Couter02 = () => {
const [cnt, setCnt] = useState(0);
useEffect(() => {
console.log("Effect is running");
const id = setInterval(() => {
console.log("COUTER UPDATE", cnt);
setCnt(cnt + 1);
}, 1000);
return () => {
console.log("EFFECT IS CLEARED");
clearInterval(id);
};
}, [cnt]);
return <>{cnt}</>;
};
const Couter03 = () => {
const [cnt, setCnt] = useState(0);
const [step, setStep] = useState(1);
useEffect(() => {
console.log("use Effect start");
const id = setInterval(() => {
setCnt((c) => {
console.log("COUTER UPDATE", c);
return c + step;
});
}, 1000);
return () => {
clearInterval(id);
console.log("use Effect cleanUp");
};
}, [step]);
return (
<>
<div>{cnt}</div>
<input value={step} onChange={(e) => setStep(Number(e.target.value))} />
</>
);
};
- ์ด๋ ๊ฒ ๋ง๋ค์๋๋, map ์์ ๋ชจ๋ ์ปดํฌ๋ํธ๋ฅผ ์ฌ ๋๋๋ง ํ๋๋ผ.
function App() {
const titles = [
{ title: "useDeviceOrientation", JSXElemnet: Hook01 },
{ title: "useFavicon", JSXElemnet: Hook02 },
{ title: "useGeolocation", JSXElemnet: Hook03 },
{ title: "useKeyPress", JSXElemnet: Hook04 },
{ title: "useLocalStorage", JSXElemnet: Hook05 },
{ title: "useMousePosition", JSXElemnet: Hook06 },
{ title: "useOnline", JSXElemnet: Hook07 },
];
return (
<div className="App">
<h1>Super Hooks !</h1>
{titles.map((e, i) => (
<Section title={e.title}>{e.JSXElemnet()}</Section>
))}
</div>
);
}
- useEffect ๋ ๋ฐ๋๋ผ๋ณ์๋ฅผ ์ด๋ค๋ฉด??? , ๋ณ์๋ฅผ ์ ํ ๋ฐ๊ฟ ์ ์๋ค.
import { useState, useEffect } from "react";
export default () => {
let pos = { x: 0, y: 0 };
const [state, setState] = useState({ x: 0, y: 0 });
const [lock, setLock] = useState(false);
const lockScroll = () => {
console.log("lock");
setLock(true);
};
const unlockScroll = () => {
setLock(false);
};
useEffect(() => {
const handleChange = (e) => {
if (lock) {
console.log(`is Lock ${lock}`);
window.scrollTo(pos.x, pos.y);
} else {
pos = { x: window.scrollX, y: window.scrollY };
console.log(`scrolled ${pos.x} ,${pos.y}`);
}
};
window.addEventListener("scroll", handleChange);
return () => {
window.removeEventListener("scroll", handleChange);
};
}, [lock]);
return [lock, { lockScroll, unlockScroll }];
};
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
import {
useDeviceOrientation,
useFavicon,
useGeolocation,
useKeyPress,
useLocalStorage,
useMousePosition,
useOnline,
useLockScroll,
} from "./hooks";
const Section = ({ title, children }) => {
return (
<>
<div>{title}</div>
{children}
</>
);
};
function App() {
// const titles = [
// { title: "useDeviceOrientation", JSXElemnet: Hook01 },
// { title: "useFavicon", JSXElemnet: Hook02 },
// { title: "useGeolocation", JSXElemnet: Hook03 },
// { title: "useKeyPress", JSXElemnet: Hook04 },
// { title: "useLocalStorage", JSXElemnet: Hook05 },
// { title: "useMousePosition", JSXElemnet: Hook06 },
// { title: "useOnline", JSXElemnet: Hook },
// ];
return (
<div className="App">
{/* <h1>Super Hooks !</h1>
{titles.map((e, i) => (
<Section title={e.title}>{e.JSXElemnet()}</Section>
))} */}
<Section title={"useDeviceOrientation"}>
<Hook01 />
</Section>
<Section title={"useFavicon"}>{Hook02()}</Section>
<Section title={"useGeolocation"}>
<Hook03 />
</Section>
<Section title={"useKeyPress"}>
<Hook04 />
</Section>
<Section title={"useKeyPress"}>
<Hook05 />
</Section>
<Section title={"useMousePosition"}>
<Hook06 />
</Section>
<Section title={"useOnline"}>
<Hook07 />
</Section>
<Section title={"useLockScroll"}>
<Hook08 />
</Section>
</div>
);
}
const Hook01 = () => {
const { alpha, beta, gamma } = useDeviceOrientation();
return (
<ul>
<li>alpha: {alpha}</li>
<li>beta: {beta}</li>
<li>gamma: {gamma}</li>
</ul>
);
};
const Hook02 = () => {
const setFavicon = useFavicon("https://www.google.com/favicon.ico");
return (
<>
<button onClick={() => setFavicon("https://facebook.com/favicon.ico")}>
change favicon
</button>
</>
);
};
const Hook03 = () => {
const {
coords: { lat, long },
error,
} = useGeolocation();
// console.log(lat, long);
return (
<ul>
<li>Latitude: {lat}</li>
<li>Longitude: {long}</li>
<li>GeoLocation error: {error === null ? "null" : "error"}</li>
</ul>
);
};
const Hook04 = () => {
const kPressed = useKeyPress("k");
const iPressed = useKeyPress("i");
const mPressed = useKeyPress("m");
const cPressed = useKeyPress("c");
const hPressed = useKeyPress("h");
return (
<ul>
<li>kPressed: {kPressed && "k"}</li>
<li>iPressed: {iPressed && "i"}</li>
<li>mPressed: {mPressed && "m"}</li>
<li>cPressed: {cPressed && "c"}</li>
<li>hPressed: {hPressed && "h"}</li>
<li>iPressed: {iPressed && "i"}</li>
</ul>
);
};
const Hook05 = () => {
const [currentLS, setLS] = useLocalStorage("JWT", "1234");
return (
<>
<ul>
<li>
<div>Current Value: {currentLS}</div>
<div>
<button onClick={() => setLS("1234")}>Set value: 1234</button>
<button onClick={() => setLS(null)}>Clear LS</button>
</div>
</li>
</ul>
</>
);
};
const Hook06 = () => {
const { x, y } = useMousePosition();
return (
<>
<ul>
<li>Mouse X: {x}</li>
<li>Mouse Y: {y}</li>
</ul>
</>
);
};
const Hook07 = () => {
const isOnline = useOnline();
return (
<>
<div>Are we online ? {isOnline ? "YES" : "NO"}</div>
</>
);
};
const Hook08 = () => {
const [isLocked, { lockScroll, unlockScroll }] = useLockScroll();
return (
<>
<div>is Locked ? {isLocked ? "YES" : "NO"}</div>
<button onClick={() => lockScroll()}>lockScroll</button>
<button onClick={() => unlockScroll()}>unlockScroll</button>
</>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
export { default as useDeviceOrientation } from "./useDeviceOrientation";
export { default as useFavicon } from "./useFavicon";
export { default as useGeolocation } from "./useGeolocation";
export { default as useKeyPress } from "./useKeyPress";
export { default as useLocalStorage } from "./useLocalStorage";
export { default as useMousePosition } from "./useMousePosition";
export { default as useOnline } from "./useOnline";
export { default as useLockScroll } from "./useLockScroll";
- useDeviceOrientation
import { useState, useEffect } from "react";
export default () => {
const [state, setState] = useState({ alpha: null, beta: null, gamma: null });
useEffect(() => {
const handleOri = (e) => {
setState({
alpha: e.alpha,
beta: e.beta,
gamma: e.gamma,
});
};
window.addEventListener("deviceorientation", handleOri, true);
return () => {
window.removeEventListener("deviceorientation", handleOri, true);
};
}, []);
return { ...state };
};
- useFavicon
export default (url) => {
const setFavicon = (url) => {
const El = document.querySelector("link#favicon");
if (El && El.href) {
El.href = url;
}
};
setFavicon(url);
return setFavicon;
};
- useFavicon - nico
import { useEffect } from "react";
export function useFavicon(initialFavicon) {
const setFavicon = (href) => {
const link =
document.querySelector("link[rel*='icon']") ||
document.createElement("link");
link.rel = "shortcut icon";
link.href = href;
const [head] = document.getElementsByTagName("head");
head.appendChild(link);
};
useEffect(() => {
setFavicon(initialFavicon);
}, [initialFavicon]);
return setFavicon;
}
- useGeolocation
import { useState, useEffect } from "react";
export default () => {
const [state, setState] = useState({
coords: { lat: null, long: null },
error: null,
});
useEffect(() => {
const succ = (pos) => {
const { latitude: lat, longitude: long } = pos.coords;
setState((pre) => ({ ...pre, coords: { lat, long } }));
};
const error = (err) => {
setState((pre) => ({ ...pre, error: true }));
};
navigator.geolocation.getCurrentPosition(succ, error);
}, []);
return state;
};
- useKeyPress
import { useState, useEffect } from "react";
export default (i) => {
const [key, setKey] = useState(false);
useEffect(() => {
const keyDownHandler = (e) => {
const keyName = e.key;
if (keyName === i) {
setKey(() => true);
}
};
const keyUpHandler = (e) => {
const keyName = e.key;
if (keyName === i) {
setKey(() => false);
}
};
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
return () => {
document.removeEventListener("keydown", keyDownHandler, false);
document.removeEventListener("keyup", keyUpHandler, false);
};
}, [i]);
return key;
};
- useLocalStorage
import { useState } from "react";
//key ์ด๋ฆ๊ณผ, ์ด๊ธฐ๊ฐ์ ์ง์ ํด ์ค๋ค.
//๋ฐํ์ผ๋ก ํ์ฌ key์ ๋์ํ๋ value๊ฐ์ ์ฃผ๊ณ , ๋ณ๊ฒฝํ ์ ์๋ ํจ์ ์ ๊ณต
export default (key, initalValue) => {
const [value, setValue] = useState(initalValue);
const setLS = (nValue) => {
localStorage.setItem(key, nValue);
setValue(nValue);
};
return [value, setLS];
};
- useLocalStorage - nico
import { useState } from "react";
export function useLocalStorage(name, initialValue) {
const [currentValue, changeValue] = useState(() => {
try {
const item = localStorage.getItem(name);
return item ? JSON.parse(item) : initialValue;
} catch (e) {
return initialValue;
}
});
const updateValue = (newValue) => {
try {
changeValue(newValue);
localStorage.setItem(name, JSON.stringify(newValue));
} catch (e) {
console.log(e);
}
};
return [currentValue, updateValue];
}
- useMousePosition
import { useState, useEffect } from "react";
export default () => {
const [state, setState] = useState({ x: 0, y: 0 });
useEffect(() => {
const mouseMoveH = (e) => {
// console.log(`
// Screen X/Y: ${e.screenX}, ${e.screenY}
// Client X/Y: ${e.clientX}, ${e.clientY}`);
if (e.clientX && e.clientY) {
setState({ x: e.clientX, y: e.clientY });
}
};
document.addEventListener("mousemove", mouseMoveH);
return () => {
console.log("EFFECT CLEARED");
document.removeEventListener("mousemove", mouseMoveH);
};
}, []);
return state;
};
- useOnline
import { useState, useEffect } from "react";
export default () => {
const [state, setState] = useState(navigator.onLine);
useEffect(() => {
const handleChange = () => {
setState(navigator.onLine);
};
window.addEventListener("online", handleChange);
window.addEventListener("offline", handleChange);
return () => {
window.removeEventListener("online", handleChange);
window.removeEventListener("offline", handleChange);
};
}, []);
return state;
};
- useLockScroll
import { useState, useEffect } from "react";
export default () => {
//let pos = { x: 0, y: 0 };
const [state, setState] = useState({ x: 0, y: 0 });
const [lock, setLock] = useState(false);
const lockScroll = () => {
console.log("lock");
setLock(true);
};
const unlockScroll = () => {
setLock(false);
};
useEffect(() => {
const handleChange = (e) => {
if (lock) {
window.scrollTo(state.x, state.y);
} else {
setState({ x: window.scrollX, y: window.scrollY });
// console.log(`scrolled ${state.x} ,${state.y}`);
}
};
window.addEventListener("scroll", handleChange);
return () => {
window.removeEventListener("scroll", handleChange);
};
}, [lock]);
return [lock, { lockScroll, unlockScroll }];
};
- useLockScroll -nico
import { useState } from "react";
export function useLockScroll() {
const [initialScroll] = useState(document.body.style.overflow);
const [isLocked, setIsLocked] = useState(false);
const lockScroll = () => {
document.body.style.overflow = "hidden";
setIsLocked(true);
};
const unlockScroll = () => {
document.body.style.overflow = initialScroll;
setIsLocked(false);
};
return [isLocked, { lockScroll, unlockScroll }];
}