react μ€ν°λμμ 리μ‘νΈλ₯Ό λ€λ£¨λ κΈ°μ μ΄λΌλ μ± μ μ μ νκ³ μ΄ μ± μ μ½κ³ λ°°μ΄ κ²μ λ°νμΌλ‘ μμ±λμλ€.
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
κ°μ λ°κΎΈμ΄μΌ ν λλ 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 곡μ λ¬Έμ