์ปดํฌ๋ํธ ๋ฆฌ๋ ๋๋ง
์ปดํฌ๋ํธ๊ฐ ๋ฆฌ๋ ๋๋ง ๋๋ ๊ฒฝ์ฐ๋ 2๊ฐ์ง ์
๋๋ค.
props๊ฐ ๋ณํ๋ ๊ฒฝ์ฐ
state๊ฐ ๋ณํ๋ ๊ฒฝ์ฐ
์๋์ ๋ ์ปดํฌ๋ํธ๊ฐ ์์ต๋๋ค.
๋ ๋๋ง์ด ๋๋ ๊ฒ์ console.log๋ก ์ฐ์ด๋ณด๊ฒ ์ต๋๋ค.
(ํจ์์ด๊ธฐ ๋๋ฌธ์ ๋ด๋ถ๊ฐ ๋์ํ๋ค๋ฉด console.log()๋ฅผ ๋์์ํฌ ๊ฒ ์
๋๋ค.)
import { useState } from "react";
import ChildComponent from "./ChildComponent";
const ParentComponent = () => {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(count + 1);
};
console.log("ParentComponent");
return (
<div>
<button type="button" onClick={handleClick}>
๋ฒํผ
</button>
<ChildComponent />
</div>
);
};
export default ParentComponent;
const ChildComponent = () => {
console.log("ChildComponent");
return <button onClick={null}>ํ๋ฆฐํธ</button>;
};
export default ChildComponent;
๋ฒํผ์ ํด๋ฆญํ ๋๋ง๋ค ์ปดํฌ๋ํธ๊ฐ ๋ฆฌ๋ ๋๋ง๋๋ค.
React.memo ์์
React.memo
: props check
props
๊ฐ ๋ฐ๋์ง ์๋๋ค๋ฉด ๊ฐ์ ์ฐ์ฐ์ ๋ค์ ํ์ง ์๋๋ก ๋ฉ๋ชจ๋ฆฌ์ ์ด์
ํ๋ Hoc(๊ณ ์ฐจํจ์)
props
๊ฐ ๋ณํ์ง ์๋๋ค๋ฉด React.memo
๋ฅผ ํตํด ์๋์ ๊ฐ์ด ์ฌ์ฐ์ฐ์ ๋ง์ ์ ์๋ค.
import { memo } from "react";
const ChildComponent = () => {
console.log("ChildComponent");
return <button onClick={null}>ํ๋ฆฐํธ</button>;
};
export default memo(ChildComponent);
์ด๋ฒ์๋ props
๋ฅผ ์ง์ ๋๊ฒจ๋ณด์
import { useState } from "react";
import ChildComponent from "./ChildComponent";
const ParentComponent = () => {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(count + 1);
};
const handleLog = () => {};
console.log("ParentComponent");
return (
<div>
<button type="button" onClick={handleClick}>
๋ฒํผ
</button>
<ChildComponent onLog={handleLog} />
</div>
);
};
export default ParentComponent;
import { memo } from "react";
const ChildComponent = ({ onLog }) => {
console.log("ChildComponent");
return <button onClick={onLog}>ํ๋ฆฐํธ</button>;
};
export default memo(ChildComponent);
์ฌ๊ธฐ์ ์ฃผ๋ชฉํ ๋ถ๋ถ์ด ๋ถ๋ช
props
๋ ๊ฐ์ handleLog
๊ฐ ๋ค์ด์๋๋ฐ ์๋์ ๊ฐ์ด ChildComponent๊ฐ ์ฐํ๋ค๋ ๊ฒ์ด๋ค.
React ํจ์์์๋ ๋ด๋ถ์ ๋ก์ง์ ์์๋๋ก ์ฌ์คํ์ ํ๊ธฐ๋๋ฌธ์ handleLog
๋ ๋งค๋ฒ ๋ค๋ฅธ ๋ฉ๋ชจ๋ฆฌ์ ์ ์ฅ์ด ๋๋ฏ๋ก ์ฌ์ค ๋ค๋ฅธ ํจ์๋ผ๊ณ ๋ด์ผํ๋ค.
์ฌ์ฐ์ฐ์ ๋ง๊ธฐ ์ํด = ์ฆ ๊ฐ์ ๋ฉ๋ชจ๋ฆฌ๋ก ๋๊ธฐ ์ํด
useMemo, useCallback + React.memo ์์
React.useMemo
vs React.useCallback
: state check
์ ๋๊ฐ์ hook
์ ์ด๋ค useMemo
๋ ๊ฐ, useCallback
์ ํจ์๋ค.
์ฌ๊ธฐ์๋ handleLog
๋ ํจ์์ด๊ธฐ๋๋ฌธ์ useCallback
์ผ๋ก ๊ฐ์ธ์ค๋ค.
import { useCallback, useState } from "react";
import ChildComponent from "./ChildComponent";
const ParentComponent = () => {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(count + 1);
};
const handleLog = useCallback(() => {}, []);
console.log("ParentComponent");
return (
<div>
<button type="button" onClick={handleClick}>
๋ฒํผ
</button>
<ChildComponent onLog={handleLog} />
</div>
);
};
๋ชจ๋ ์ปดํฌ๋ํธ๋ ๋ฉ๋ชจ๋ฆฌ์ ์ด์
ํ๋ฉด ์ข์๊ฐ?
๊ฒฐ๋ก ์ ๊ทธ๋ ์ง๋ ์๋ค.
๋ฉ๋ชจ๋ฆฌ์ ์ด์
์์ฒด๊ฐ ๋ฆฌ์์ค๋ฅผ ์ฐ๋ ํ์์ด๊ธฐ ๋๋ฌธ์ ๋ฐ๋ณต์ ์ผ๋ก ๋ ๋๋ง์ ๊ฐ์ ํ ๊ฒฝ์ฐ์๋ง ์ฐ๋๋ก ํ์!