Components often need to change what’s on the screen as a result of an interaction. Typing into the form should update the input field, clicking “next” on an image carousel should change which image is displayed, clicking “buy” should put a product in the shopping cart. Components need to “remember” things: the current input value, the current image, the shopping cart. In React, this kind of component-specific memory is called state.
컴포넌트는 상호작용의 결과로서 화면의 무언가를 변경해야 하는 경우가 자주 필요하다. 폼에 입력하는 것은입력 필드가 업데이트되고, 이미지 케러셀에서 "next"를 클릭하면 이미지가 변경되어야 하고, "구매"를 클릭하면 쇼핑 카드에 물건을 담아야 한다. 컴포넌트는 현재 입력 값, 이미지, 쇼핑 카드를 기억할 필요가 있다. 리액트 안에서, 이런 종류의 컴포넌트별 메모리를 state라고 부른다.
-> 이벤트가 발생하거나, 내용이 변경될 때 내용을 변경하고, 저장하는 변수
일반 변수로 충분하지 않은 상황이 존재하기 때문이다.
import { useState } from 'react'
function App() {
let state = 0;
return (
<div>
<h1>{state}</h1>
<button onClick={() =>{
state = state + 1
console.log(state)
}}
>
+++
</button>
</div>
)
}
export default App;
<button>
태그의 onClick
을 통해 지역변수인 state
를 증가시키고 있지만, 두 가지 이유로 변경사항이 화면에 표시되지 않는다.
1. 지역 변수는 렌더링 간에 유지가 되지 않는다.
-> 리액트는 컴포넌트를 두 번째로 렌더링할 때 지역 변수에 대한 변경 사항을 고려하지 않고 처음부터 랜더링한다.
2. 지역 변수를 변경해도 렌더링을 발동시키지 않는다.
-> 리액트는 새로운 데이터로 컴포넌트를 다시 렌더링해야 한다는 것을 인식하지 못한다.
The
[
and]
syntax here is called array destructuring and it lets you read values from an array. The array returned by useState always has exactly two items.
[
와 ]
는 배열 구조분해라고 하고, 배열 안의 값을 읽을 수 있다. useState가 반환하는 배열에는 두 가지 요소가 항상 존재한다.
const [state, setState] = useState(0);
버튼이 클릭될 때마다 state의 값을 1씩 증가시키는 컴포넌트
import { useState } from 'react'
function App() {
const [state, setState] = useState(0);
return (
<div>
<h1>{state}</h1>
<button onClick={() =>{
setState(state+1)
}}
>
+++
</button>
</div>
)
}
export default App;
리액트에서 useState
를 비롯해서 use
로 시작하는 함수들을 훅(hook)
이라고 부른다.
훅은 리액트가 렌더링 중일 때만 사용할 수 있다. 이를 통해 다양한 리액트 기능을 연결할 수 있다.
state는 화면의 컴포넌트에 지역적이다. 동일한 컴포넌트를 두 군데에서 렌더링하면 각각 완전히 별개의 state를 갖게 된다. 이 중 하나를 변경해도 다른 컴포넌트에는 영향을 미치지 않는다.
부모 컴포넌트는 자식 컴포넌트의 state 여부조차 알지 못한다. props와 달리 state는 선언하는 컴포넌트 외에 완전히 비공개이다. 따라서 다른 컴포넌트에 영향을 주지 않고 state 수정할 수 있다.
const Light = ({light}) => {
return (
<div>
{light === "ON" ? (
<p style={{backgroundColor:"orange"}}>ON</p>
): (
<p style={{backgroundColor:"gray"}}>OFF</p>
)}
</div>
)
};
export default Light;
import { useState } from 'react'
import Light from "./components/Light"
function App() {
const [light, setLight] = useState("OFF");
return (
<div>
<Light light={light}/>
<button
onClick={() => {
setLight(light === "ON" ? "OFF" : "ON");
}}>turn</button>
</div>
)
}
export default App;
Light.jsx
에서 props로 light를 받아오는 Light 컴포넌트를 정의한다. light
의 형태에 따라 내부 구조가 변경된다.
App.jsx
에서 state 변수 light를 선언하고, 초기값을 "OFF"
로 설정한다. Light 컴포넌트의 light
에 state 변수 light를 할당한다. button
태그가 클릭 됐을 때, state 변수 light의 상태를 변경한다.