[Hook] useState

강은비·2022λ…„ 1μ›” 12일
0

React

λͺ©λ‘ 보기
9/36

react μŠ€ν„°λ””μ—μ„œ λ¦¬μ•‘νŠΈλ₯Ό λ‹€λ£¨λŠ” κΈ°μˆ μ΄λΌλŠ” 책을 μ„ μ •ν–ˆκ³  이 책을 읽고 배운 것을 λ°”νƒ•μœΌλ‘œ μž‘μ„±λ˜μ—ˆλ‹€.


πŸ“Œ useState

  • v16.8 이후뢀터 useState ν•¨μˆ˜λ₯Ό μ΄μš©ν•˜μ—¬ ν•¨μˆ˜ν˜• μ»΄ν¬λ„ŒνŠΈμ—μ„œλ„ stateλ₯Ό μ΄μš©ν•  수 μžˆλ‹€.

    πŸ’‘ stateλŠ” μ»΄ν¬λ„ŒνŠΈκ°€ 자체적으둜 μ§€λ‹Œ μƒνƒœκ°’μœΌλ‘œ, μ»΄ν¬λ„ŒνŠΈ λ‚΄μ—μ„œ 값을 μ—…λ°μ΄νŠΈν•  수 μžˆλ‹€.

  • useState ν•¨μˆ˜λ₯Ό ν˜ΈμΆœν•˜λ©΄ 배열이 λ°˜ν™˜λ˜λŠ”λ°, 첫번째 μ›μ†ŒλŠ” ν˜„μž¬ μƒνƒœκ°’μ΄κ³ , λ‘λ²ˆμ§Έ μ›μ†ŒλŠ” μƒνƒœλ₯Ό λ°”κΎΈμ–΄ μ£ΌλŠ” setter ν•¨μˆ˜μ΄λ‹€.
  • useState ν•¨μˆ˜λ₯Ό ν˜ΈμΆœν•  λ•Œ 초기 μƒνƒœκ°’μ„ 인자둜 μ „λ‹¬ν•œλ‹€.
  • setState을 ν˜ΈμΆœν•˜λ©΄ 인자둜 전달받은 κ°’μœΌλ‘œ μƒνƒœκ°’μ΄ μ—…λ°μ΄νŠΈλ˜κ³  μ»΄ν¬λ„ŒνŠΈκ°€ λ¦¬λ Œλ”λ§λœλ‹€.
import React, { useState } from 'react';

function Counter() {
    // λ°°μ—΄ 비ꡬ쑰화 ν• λ‹Ή
    const [number, setNumber] = useState(0);
    
    const onIncrease = () => {
        setNumber(number + 1);
    };
    
    const onDecrease = () => {
        setNumber(number - 1);
    };
    
    return (
        <div>
            <h1>{number}</h1>
            <button onClick = {onIncrease}>+1</button>
            <button onClick = {onDecrease}>-1</button>
        </div>
    );

}
export default Counter;

✨ ν•¨μˆ˜ν˜• μ—…λ°μ΄νŠΈ

  • λ§Œμ•½ μ΄μ „μ˜ μƒνƒœκ°’μ„ μ°Έμ‘°ν•˜κ³  μ‹Άλ‹€λ©΄, setState에 ν•¨μˆ˜ 인자λ₯Ό μ „λ‹¬ν•˜λ©΄ λœλ‹€.
  • 이 ν•¨μˆ˜ μΈμžλŠ” μ΄μ „μ˜ μƒνƒœκ°’μ„ 인자둜 λ°›κ³  μ—…λ°μ΄νŠΈλœ μƒνƒœκ°’μ„ λ°˜ν™˜ν•œλ‹€.
// ν•¨μˆ˜ν˜• μ—…λ°μ΄νŠΈ
const onIncrease = () => {
    setNumber(prevNumber => prevNumber + 1);
}
const onDecrease = () => {
    setNumber(prevNumber => prevNumber - 1);
}

✨ state μ‚¬μš© μ‹œ μ£Όμ˜μ‚¬ν•­

  • state 값을 λ°”κΎΈμ–΄μ•Ό ν•  λ•ŒλŠ” setState ν˜Ήμ€ useStateλ₯Ό 톡해 전달받은 setter ν•¨μˆ˜λ₯Ό μ‚¬μš©ν•΄μ•Όλ§Œ ν•œλ‹€.
// 잘λͺ»λœ μ½”λ“œ
this.state.number = this.state.number + 1;
this.state.array = this.state.array.push(2);
this.state.object.value = 5;

const [object, setObject] = useState({a: 1, b: 1});
object.b = 2;
  • λ°°μ—΄μ΄λ‚˜ 객체λ₯Ό μ—…λ°μ΄νŠΈν•΄μ•Ό ν•  λ•ŒλŠ” λ°°μ—΄μ΄λ‚˜ 객체 사본을 λ§Œλ“€κ³  κ·Έ 사본에 값을 μ—…λ°μ΄νŠΈν•œ ν›„ κ·Έ μ‚¬λ³Έμ˜ μƒνƒœλ₯Ό setState ν˜Ήμ€ setter ν•¨μˆ˜ν†΅ν•΄ μ—…λ°μ΄νŠΈν•œλ‹€.

μ°Έκ³ : React 곡식 λ¬Έμ„œ

0개의 λŒ“κΈ€