Class Component vs Functional Component

์ฟ ๊ณ ๋ƒฅ(KuruCat)ยท2022๋…„ 5์›” 31์ผ
0

๐Ÿ“Œ ์ฐธ๊ณ ์ž๋ฃŒ

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๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์— ๋ถˆํ•„์š”ํ•œ ํ˜ผ๋™์„ ์ค„์ผ ์ˆ˜ ์žˆ๋‹ค๊ณ  ํ•œ๋‹ค.

profile
FEdeveloper๋ชฉํ‘œ๋กœ ๊ณต๋ถ€์ค‘

0๊ฐœ์˜ ๋Œ“๊ธ€