React useState

devyunie·2024년 8월 22일

React

목록 보기
11/20
post-thumbnail

State

ex) 쇼핑몰에서 구매를 누르면 장바구니에 담겨야한다

  • 각각의 컴포넌트가 독립적으로 가지고 있는 데이터 저장 공간
  • 상태가 컴포넌트의 렌더링에 영향을 미침
  • 상태가 변경되면 컴포넌트가 리렌더링 함
export default function EventComponent() {
	let count = 0;
	const onIncrease = () => {
		count ++;
		console.log(count);
	}
	return(
		<h1>{count}</h1>
		<button onClick={onIncrease}>숫자 +</button>
	)
}
  • console 창에는 값이 증가는 하지만 'h1' 태그에서는 값이 변하지 않는 문제 발생
  • !! state 활용

선언방법

useState (훅함수)

const[상태변수, 상태변경함수] = useState<상태변수타입>(초기값);
상태변수는 반드시 상태변경함수를 통해서 변경해야 리렌더링됨

import React, { useState } from 'react'

export default function StateComponent() {
	//let count:number = 0;
	const [count, setCount] = useState<number>(0);
	//let counts : number[] = [];
	const [counts, setCoints] =useState<number[]>([]);
	const onIncrease = () => {
		setCount(count + 1);
		//상태변수는 반드시 상태변경함수를 통해서 변경해야 리렌더링됨
		// count++;
		// console.log(count);
	};
	return (
		<div>
			<h1>{count}</h1>
			<button onClick={onIncrease}>+</button>
		</div>
	)
}

‼️

  • 상태 변경 함수를 사용하여 상태를 변경한다고 바로 변경되지 않음
  • 함수가 끝나고 렌더링 되는 시점에 적용됨
//0
setCount(count+1)
//0
setCount(count+2)
//0
setCount(count+3)
  • 상태 변경 함수에 콜백 함수를 전달하면 해당 콜백 함수는 누적되어 실행됨
//상태 count : 0
//argCount : 0
console.log('상태 count : '+ + count)
setCount((argCount)=> {
	console.log('argCount: ' + argCount)
	return argCount + 1
});

//상태 count :0
//argCount : 1
console.log('상태 count : '+ + count)
	setCount((argCount)=> {
	console.log('argCount: ' + argCount)
return argCount + 2
});

//상태 count :0
//argCount : 3
console.log('상태 count : '+ + count)
setCount((argCount)=> {
	console.log('argCount: ' + argCount)
	return argCount + 3
});
  • 상태 변경하는 작업이 한번에 여러번 실행된다면 임시 변수를 활용하여 사용할수도 았다.
let tmp = 0;
tmp = count;
tmp+=1;
tmp+=2
tmp+=3;
setCount(tmp);
  • Total 상태변경 함수를 생성하여 이용
const [total, setTotal]=useState<number>(0);
  • setTotal 에서 기존의 count 값을 사용하기 때문에 동작이 한단계 전 단계로 동작함

실패

setCount(count + 1);
setTotal(total + count);
  • 임시 변수를 사용하여 변경 결과 값을 미리 저장 하고 사용하면 위의 문제를 해결 할수가 있다

해결법

const newCount = count +1;
setCount(newCount);
setTotal(total + newCount);
  • 배열에 요소를 추가하지만 실제 배열 주소가 바뀌지 않았기 때문에 변경을 인식 못함

실패

counts.push(newCount);
console.log(counts);
setCounts(counts);

//화면 출력
// 0, 0
// 1, 0 
// 2, 0 
  • 타입이 배열 혹은 객체 형태인 상태는 반드시 새로운 배열 혹은 객체를 생성하고 변경해야 인식함

해결

const newCounts = [...counts, newCount];
setCounts(newCounts);

//화면출력
//  1, 0
//  2, 01
//  3. 012
  • 문자열
const [comment,setCommet] = useState<string>('');
let comm = ''; //상태변수가 아님
const onChangeHandler = (event: ChangeEvent<HTMLInputElement>) =>{
	comm = event.target.value;
	console.log(comm);
	setCommet(event.target.value);
}
  • ‼️ 만약 input으로 상태를 변경한다면 value로 그 상태를 지정해야 불일치가 발생하지 않는다.
<input value={comment} onChange={onChangeHandler}/>

  • 현재종합적인 결과 return 문
return (
	<div>
		<h1>{comm}</h1>
		<h1>{comment}</h1>
		<input value={comment} onChange={onChangeHandler}/>
		<h1> count : {count}</h1>
		<h1>total : {total}</h1>
		<h1>counts lenght: {counts.length} {counts}</h1>
		<button onClick={onIncrease}>+</button>
	</div>
)

0개의 댓글