2024-03-11.md
๐กDIL: ๋ชจ๋ ๋ฆฌ์กํธ ๋ฅ ๋ค์ด๋ธ, 2์ฃผ์ฐจ-1
์คํฐ๋: ์๊ฐ CS, https://github.com/monthly-cs/2024-03-modern-react-deep-dive
์ค๋ ์งํ: ๊ฐ์ธ๊ณต๋ถ
DIL-week2-1_2024-03-11
| DIL ์ฃผ์ฐจ | ๋ฒ์ | ๋ด์ฉ | ์ค๋์ฐจ ์ง๋ | | -------- | ------ | ------------------------------- | ----------- | | 2์ฃผ์ฐจ | 3, 5์ฅ | ๋ฆฌ์กํธ ํ ๊ณผ ์ํ๊ด๋ฆฌ ๋ผ์ด๋ธ๋ฌ๋ฆฌ | 189~194p |
์ค๋ ์ฝ์ ๋ด์ฉ์ markdown์ผ๋ก ๊ฐ๋จํ ๋ฉ๋ชจ
์ฝ์ ์๊ฐ: 10์๋ฐ~12์
React Hook ํํค์น๊ธฐ
useState
const [state, setState] = useState(initialState); // initial state์ด ์๋ค๋ฉด ์ด๊ธฐ๊ฐ์ undefined
- ํจ์ ์ปดํฌ๋ํธ ๋ด๋ถ์์ ์ํ๋ฅผ ์ ์, ์ํ๋ฅผ ๊ด๋ฆฌํ ์ ์๊ฒ ํด์ฃผ๋ ํ
- ๋งค๋ฒ ๋ ๋๋ง์ด ๋ฐ์๋ ๋๋ง๋ค, ํจ์๋ ์๋กญ๊ฒ ์คํ๋๊ณ , ์๋กญ๊ฒ ์คํ๋๋ ํจ์์ ๊ฐ์ด ์ด๊ธฐํ๋๋ค.
- ์ด๋ฅผ ํด๊ฒฐํ๊ธฐ ์ํด closure ์ฌ์ฉ
- ์ค์ ๋ฆฌ์กํธ ์ฝ๋์์๋ useReducer๋ฅผ ์ด์ฉ
- ํ
์ ๊ตฌํ์ฒด ํ๊ณ ์ฌ๋ผ๊ฐ๋ฉด?
__SECRET_INTERNAL_DO_NOT_USE_OR_YOU_WILL_FIRED
- ํ
์ ๊ตฌํ์ฒด ํ๊ณ ์ฌ๋ผ๊ฐ๋ฉด?
=> MyReact์ useState์ด ๋ฐํํ๋ setState ๋ด์์ ๋๋๋ง ๊ตฌํํด๋ณด๋ ค ํ๋๋ฐ ์คํจ
- Uncaught RangeError: Maximum call stack size exceeded
- MyReact.global ๊ฐ์ฒด์์ index๋ฅผ ๊ด๋ฆฌํด์ ํด๊ฒฐํ ์ ์์ ๊ฒ์ผ๋ก ๋ณด์ด๋๋ฐ ์ ์ ๋ชฉ์ ์์ ๋ฒ์ด๋๋ ๊ฒ ๊ฐ์์ ์ค์ง -> ํ์ต ์ง๋ ๋ค ๋๊ฐ๋ด์ ์ฌ์ฌํ๋ฉด ์ฌ๋์
import React from "react";
export default function MyUseState() {
return MyReact;
}
const MyReact = (() => {
interface Global {
states: any[];
}
const global: Global = {
states: [],
};
let index = 0;
type SetStateFunction = (value: any) => void;
function useState(initState?: any): [any, SetStateFunction] {
const currentIndex = index;
if (typeof global.states[currentIndex] === "undefined") {
global.states[currentIndex] =
typeof initState !== "undefined" ? initState : null;
}
const currentState = global.states[currentIndex];
const setState: SetStateFunction = (value) => {
global.states[currentIndex] = value;
forceUpdate();
};
index = index + 1;
return [currentState, setState];
}
const [value, setValue] = useState(0);
let render: React.FC<{ value: any }> = ({ value }) => (
<section>
<aside>
<label>My UseState Hook</label>
<div>{value}</div>
<button onClick={() => setValue(value + 1)}>+</button>
</aside>
</section>
);
const forceUpdate = () => {
render = (newValue) => render({ value: newValue });
return render(value);
};
return render(value);
})();