게시글은 리액트 공부용이며 출처를 제시합니다.
출처: 소플의 처음 만난 React, 리액드를 다루는 기술, 모던 자바스크립트 deep dive
Hooks 사용하며 Hooke의 종류는 다양하지만 useState
를 사용하여 state값을 업데이트 하자!
객체 비구조화 할당과 비슷하다. 배열 안에 들어 있는 값을 쉽게 추출할 수 있다.
const array = [1,2];
const one = array[0];
const two = array[1];
//비구조화할당하기
const array = [1,2];
const [one, two] = array;
import React, { useState } from "react";
const FunctionalState = () => {
const [message, setMessage] = useState("");
const onClickEnter = () => setMessage("안녕하세요");
const onClickLeave = () => setMessage("안녕히가세요");
return (
<div>
<button onClick={onClickEnter}>입장</button>
<button onClick={onClickLeave}>퇴장</button>
<h1>{message}</h1>
</div>
);
};
export default FunctionalState;
import React, { useState } from "react";
const FunctionalState = () => {
const [message, setMessage] = useState("");
const onClickEnter = () => setMessage("안녕하세요");
const onClickLeave = () => setMessage("안녕히가세요");
const [color, setColor] = useState("black");
return (
<div>
<button onClick={onClickEnter}>입장</button>
<button onClick={onClickLeave}>퇴장</button>
<h1 style={{ color }}>{message}</h1>
<button style={{ color: "green" }} onClick={() => setColor("green")}>
초록색
</button>
<button style={{ color: "red" }} onClick={() => setColor("red")}>
빨간색
</button>
<button style={{ color: "blue" }} onClick={() => setColor("blue")}>
파란색
</button>
</div>
);
};
export default FunctionalState;
state를 직접 변경하면 안된다.
배열이나 객체를 업데이트 할 때는 사본을 만들고 그 사본에 값을 업데이트 한 후, 그 사본의 상태를 setState를 통해 업데이트 한다. 스프레드 연산자 사용하기
불변성 지키기