๐ ์ฐธ๊ณ ์๋ฃ
Differences between Functional Components and Class Components in React
React Docs
React Class Component vs. Functional Component: Whatโs the Difference
Build the future of communications.
๐ ๋ฐฐ๊ฒฝ์ง์
React์์๋ ๋๊ฐ์ง ๋ฐฉ๋ฒ์ผ๋ก Component๋ฅผ ์์ฑํ ์ ์๋๋ฐ, function Component์ Class componenet๊ฐ ๊ทธ ๋๊ฐ์ง์ด๋ค.
React 16.8์์ hooks๊ฐ ๋ฑ์ฅํ๊ธฐ ์ด์ ์๋, ์ค์ง Class Component์์๋ง state์ lifecycle methods์ ์ ๊ทผํ ์ ์์์ง๋ง ์ด์ ๋ UI๋ฅผ ๊ตฌ์ฑํ๋๋ฐ ํ์ํ ๋ชจ๋ ๊ธฐ๋ฅ์ hooks๋ก ๊ตฌํ๊ฐ๋ฅํ๊ฒ ๋์๋ค.
์ต๊ทผ์๋ function Componenet๊ฐ ์กฐ๊ธ ๋ ๋์ค์ ์ผ๋ก ์ฌ์ฉ๋๊ณ ์๋ค.
๐ ํด๋์คํ๊ณผ ํจ์ํ ์ปดํฌ๋ํธ์ ์ฐจ์ด
๐ function Componenet
- JS์ ํจ์์ ๊ฐ์ ๊ธฐ๋ฅ์ ํ๋ ์ปดํฌ๋ํธ๋ก, props๋ฅผ ์ ๋ฌ์ธ์๋ก ๋ฐ์ React elements๋ฅผ ๋ฐํํ๋ค.
- Class Component ์์ ์ฌ์ฉ๋๋ lifecycle๋ฉ์๋๋ฅผ ์ฌ์ฉํ ์ ์๋ ๋์ ,useState ๋๋ useEffect๊ฐ์ hooks๋ฅผ ํตํด ๊ฐ๋จํ๊ฒ UI๋ฅผ ๊ตฌํํ ์ ์๋ค.
๐ Class Component
- Class Comnenet๋ ๊ธฐ๋ณธ์ ์ผ๋ก React๋ก๋ถํฐ ์์๋ฐ๋๋ค.๊ทธ๋ฆฌ๊ณ Render()์ ํตํด React element๋ฅผ ๋ฐํํ๋ค.
- componentDidMount()๊ฐ์ lifecycle methods๋ฅผ ์ฌ์ฉํ ์ ์๋ค.
- Constructor์ ํตํด state๋ฅผ ๊ด๋ฆฌํ๋ค.
๐ ํจ์ํ ์ปดํฌ๋ํ ์ฃผ๋ก ์ฌ์ฉํ๋ ์ด์
โฌ๏ธํจ์ํโฌ๏ธ
const FunctionalComponent = () => {
React.useEffect(() => {
return () => {
console.log("Bye");
};
}, []);
return <h1>Bye, World</h1>;
};
โฌ๏ธํด๋์คํโฌ๏ธ
class ClassComponent extends React.Component {
componentWillUnmount() {
console.log("Bye");
}
render() {
return <h1>Bye, World</h1>;
}
}
Hook์ ์ฌ์ฉํ๋ฉด ์ปดํฌ๋ํธ๋ก๋ถํฐ ์ํ ๊ด๋ จ ๋ก์ง์ ์ถ์ํํ ์ ์์ต๋๋ค. ์ด๋ฅผ ์ด์ฉํด ๋ ๋ฆฝ์ ์ธ ํ ์คํธ์ ์ฌ์ฌ์ฉ์ด ๊ฐ๋ฅํฉ๋๋ค. Hook์ ๊ณ์ธต์ ๋ณํ ์์ด ์ํ ๊ด๋ จ ๋ก์ง์ ์ฌ์ฌ์ฉํ ์ ์๋๋ก ๋์์ค๋๋ค. ์ด๊ฒ์ ๋ง์ ์ปดํฌ๋ํธ ํน์ ์ปค๋ฎค๋ํฐ ์ฌ์ด์์ Hook์ ๊ณต์ ํ๊ธฐ ์ฝ๊ฒ ๋ง๋ค์ด์ค๋๋ค.
๋ ์์ฑ๋ฐฉ๋ฒ์ ๋น๊ตํ์์ ๋, ๋ ๊ฐ๊ฒฐํ๊ณ ์ดํดํ๊ธฐ ์ฌ์ด ์ฝ๋๋ฅผ ์์ฑํ ์ ์๊ณ ,
ํด๋์ค์ ๋นํ์ฌ ์ํ๊ด๋ จ๋ก์ง์ ์์ด์ ์ ์ง๋ณด์๊ฐ ์ฌ์ด ์ ๋๋ฌธ์ react docs์์ ๊ถ์ฅํ๊ณ ์๋ค.
์ด ๋๋ฌธ์ ๋ถํ์ํ ์ฝ๋๋ฅผ ์ต์ ํํ์ฌ ํด๋์ค๋ณด๋ค ๋์ ์ฑ๋ฅ์ ๊ธฐ๋ํ ์ ์๋ค.
๋ํ, class์์ ์ฌ์ฉ๋๋ this๋ฅผ ์ฌ์ฉํ์ง ์๊ธฐ ๋๋ฌธ์ ๋ถํ์ํ ํผ๋์ ์ค์ผ ์ ์๋ค๊ณ ํ๋ค.