๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ‘จ‍๐Ÿ’ป web.dev/fe

React ์ œ์–ด ์ปดํฌ๋„ŒํŠธ vs ๋น„์ œ์–ด ์ปดํฌ๋„ŒํŠธ

by HandHand 2022. 4. 10.

 

๐Ÿ“Œ ๋น„์ œ์–ด ์ปดํฌ๋„ŒํŠธ (uncontrolled component)

๋น„์ œ์–ด ์ปดํฌ๋„ŒํŠธ ์—์„œ ํผ ๋ฐ์ดํ„ฐ๋Š” DOM ์ž์ฒด์— ์ €์žฅ๋ฉ๋‹ˆ๋‹ค.

๋งŒ์•ฝ ํ•ด๋‹น ํผ ๋ฐ์ดํ„ฐ๋ฅผ ์ฝ์–ด์˜ค๊ณ  ์‹ถ๋‹ค๋ฉด ref ๋ฅผ ์ด์šฉํ•ด์„œ ๊ฐ’์„ PULL ํ•ด์™€์„œ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.

 

import React, { useRef } from 'react'

const UnControlledComponent = () => {
  const inputRef = useRef(null)

  const handleClick = () => {
    /** input ๊ฐ’์œผ๋กœ ํŠน์ • ๋กœ์ง์„ ์ˆ˜ํ–‰ํ•ฉ๋‹ˆ๋‹ค. */
    console.log(inputRef.current.value)
  }

  return (
    <div>
      <input type="text" ref={inputRef} />
      <button onClick={handleClick} >ํ™•์ธ</button>
    </div>
  )
}

export default UnControlledComponent

 

๐Ÿ“Œ ์ œ์–ด ์ปดํฌ๋„ŒํŠธ (controlled component)

์ œ์–ด ์ปดํฌ๋„ŒํŠธ ๋Š” ๋ณด๋‹ค React์Šค๋Ÿฌ์šด ๋ฐฉ๋ฒ• ์œผ๋กœ ๊ฐ’์„ ์ œ์–ดํ•ฉ๋‹ˆ๋‹ค.

React ์ปดํฌ๋„ŒํŠธ์˜ ์ƒํƒœ๊ฐ’์„ ์‹ ๋ขฐ ๊ฐ€๋Šฅํ•œ ๋‹จ์ผ ์ถœ์ฒ˜ (single source of truth) ๋กœ ๋งŒ๋“ค์–ด ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.

ํผ ์ž…๋ ฅ ์ปดํฌ๋„ŒํŠธ์˜ value ๊ฐ€ ํ•ด๋‹น ์ปดํฌ๋„ŒํŠธ์˜ state ์—์„œ ๊ด€๋ฆฌ๋˜๋ฉฐ ๋™๊ธฐํ™”๋˜๋Š” ๋ฐฉ์‹์ž…๋‹ˆ๋‹ค.

 

import React, { useState } from 'react'

const ControlledComponent = () => {
  const [ name, setName ] = useState('')

  const handleChange = (event) => {
    setName(event.target.value )
  }

  return (
    <div>
      <input type="text" value={name} onChange={handleChange} />
    </div>
  )
}

export default ControlledComponent

 

์ž…๋ ฅ๊ฐ’์— ๋ณ€ํ™”๊ฐ€ ์ƒ๊ธธ๋•Œ๋งˆ๋‹ค handleChange ํ•จ์ˆ˜๊ฐ€ ํ˜ธ์ถœ๋˜์–ด ์ƒํƒœ๊ฐ’์ด ๋ณ€ํ™”ํ•˜๊ณ 

์ด๋•Œ๋ฌธ์— ๋ฆฌ๋ Œ๋”๋ง์ด ๋ฐœ์ƒํ•ด ์ƒˆ๋กœ์šด ์ƒํƒœ๊ฐ’์ด input ์š”์†Œ์— ๋ฐ”์ธ๋”ฉ ๋˜๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค.

์ด๋ ‡๊ฒŒ ์ƒˆ๋กœ์šด ๊ฐ’์„ PUSH ํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ๊ตฌํ˜„ํ•˜๋Š” ํผ ์—˜๋ฆฌ๋จผํŠธ๋ฅผ ์ œ์–ด ์ปดํฌ๋„ŒํŠธ ๋ผ๊ณ  ํ•˜๋ฉฐ

์ฃผ๋กœ ์ž…๋ ฅ๊ฐ’์˜ ์ฆ‰๊ฐ์ ์ธ ๋ณ€ํ™”์— ๋Œ€์‘ํ•˜๋Š” ๋กœ์ง์„ ์ˆ˜ํ–‰ํ•ด์•ผ ํ•˜๋Š” ๊ฒฝ์šฐ์— ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค.

 

*  ์ž…๋ ฅ๊ฐ’ ๊ฒ€์ฆ (ํ˜•์‹ ๋ฐ ๊ฐ’ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ)
*  ์œ ํšจํ•œ ๊ฐ’์ธ์ง€ ๊ฒ€์ฆ ํ›„ ๋ฒ„ํŠผ ํ™œ์„ฑํ™” ๋“ฑ์˜ ์ƒํ™ฉ

 

๐Ÿ“Œ ๋‘˜ ์ค‘ ์–ด๋Š๊ฒƒ์„ ์‚ฌ์šฉํ•ด์•ผํ• ๊นŒ?

useRef ๋ฅผ ํ†ตํ•ด ๋น„์ œ์–ด ์ปดํฌ๋„ŒํŠธ๋ฅผ ๋งŒ๋“ค์–ด ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ๋ฌด์กฐ๊ฑด ๋‚˜์œ ๊ฒƒ์€ ์•„๋‹™๋‹ˆ๋‹ค.

๋•Œ์— ๋”ฐ๋ผ์„œ๋Š” ๊ฐ€๋ณ๊ณ  ๊ฐ„๋‹จํ•œ ํผ ์—˜๋ฆฌ๋จผํŠธ๋ฅผ ๋งŒ๋“ค๊ธฐ ์œ„ํ•ด ๋น„์ œ์–ด ์ปดํฌ๋„ŒํŠธ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์œ ์šฉํ•  ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค.

์ด์™€ ๊ด€๋ จํ•ด์„œ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์–ด๋–ค ๊ฒฝ์šฐ์— ์ œ์–ด ํ˜น์€ ๋น„์ œ์–ด ์ปดํฌ๋„ŒํŠธ ๋ฅผ ์‚ฌ์šฉํ•ด์•ผํ• ์ง€

์ง€ํ‘œ๊ฐ€ ๋  ์ˆ˜ ์žˆ๋Š” ์ž๋ฃŒ๊ฐ€ ์žˆ์–ด์„œ ์ฐธ๊ณ ํ•˜์—ฌ ํ™œ์šฉํ•˜๋ฉด ๋  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.

 

1

 

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

ํผ - React

Controlled and uncontrolled form inputs in React don't have to be complicated - Gosha Arinich

๋ฐ˜์‘ํ˜•

๐Ÿ’ฌ ๋Œ“๊ธ€