함수 구성 요소의 상태를 추적할 수 있다.
상태는 일반적으로 애플리케이션에서 추적해야 하는 데이터 또는 속성을 나타낸다.
함수 구성 요소를 호출하여 상태를 초기화 한다.
초기 상태를 받아들이고 두 개의 값을 반환한다.
import { useState } from "react";
function TestColor() {
const [color, setColor] = useState("");
}
첫 번째 값 color는 현재 상태이다.
두 번째 값인 setColor는 상태를 업데이트하는 데 사용되는 함수이다.
마지막으로 초기 상태를 빈 문자열로 설정한다.
컴포넌트의 아무 곳에나 상태를 포함 할 수 있다.
// App.js
import { useState } from "react";
function TestColor() {
const [color, setColor] = useState("");
return <h1>{color}</h1>
}
// index.js
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
상태를 업데이트하기 위해 상태 업데이트 함수 기능을 사용한다.
상태를 직접 업데이트해서는 안된다.
// App.js
import { useState } from "react";
function TestColor() {
const [color, setColor] = useState("");
return (
<>
<h1>My favorite color is {color}!</h1>
<button
type="button"
onClick={() => setColor("blue")}
>Blue</button>
</>
)
}
// index.js
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
useState는 string, number, boolean, array, object 및 이들의 조합을 추적하는 데 사용할 수 있다.
import { useState } from "react";
import ReactDOM from "react-dom/client";
function Car() {
const [brand, setBrand] = useState("Ford");
const [model, setModel] = useState("Mustang");
const [year, setYear] = useState("1964");
const [color, setColor] = useState("red");
return (
<>
<h1>My {brand}</h1>
<p>
It is a {color} {model} from {year}.
</p>
</>
)
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car />);
또는 하나의 상태를 사용하고 객체를 포함할 수 있다.
import { useState } from "react";
import ReactDOM from "react-dom/client";
function Car() {
const [car, setCar] = useState({
brand: "Ford",
model: "Mustang",
year: "1964",
color: "red"
});
return (
<>
<h1>My {car.brand}</h1>
<p>
It is a {car.color} {car.model} from {car.year}.
</p>
</>
)
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car />);
단일 개체를 추적하고 있으므로 구성 요소를 렌더링할 때 해당 개체를 참조한 다음 해당 개체의 속성을 참조해야 한다.
상태가 업데이트되면 전체 상태를 덮어쓴다.
단일 개체에서 특정 속성만 업데이트 하고 싶다면 setCar{{color: "blue"}}만 호출 하면 상태에서 다른 속성들은 제거된다.
Javascript 스프레드 연산자를 사용하여 나머지 속성을 유지할 수 있다.
import { useState } from "react";
import ReactDOM from "react-dom/client";
function Car() {
const [car, setCar] = useState({
brand: "Ford",
model: "Mustang",
year: "1964",
color: "red"
});
const updateColor = () => {
setCar(previousState => {
return { ...previousState, color: "blue" }
});
}
return (
<>
<h1>My {car.brand}</h1>
<p>
It is a {car.color} {car.model} from {car.year}.
</p>
<button
type="button"
onClick={updateColor}
>Blue</button>
</>
)
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car />);
state의 현재 값이 필요하기 때문에 함수에 함수를 전달해야한다.
color 뿐만 아니라 다른 속성에 대해서도 해당 속성만 업데이트가 가능하다.