컴포넌트의 상태(컴포넌트가 가질 수 있는 상태)
ex) 시계라는 컴포넌트가 있다면, state로 time을 가질 수 있다.
컴포넌트의 상태를 간편하게 업데이트 해줄 수 있게 도구를 제공
ex) state: time = 5시 ⇒ state: time = 6시
const [state, setState] = useState(초기값);
state 생성과 동시에 가져야 할 초기값을 useState 함수의 인자로 넣어주면, state와 setState라는 두가지 요소를 배열 형태로 return해준다.
현재 상태 값은 state 변수에 들어있고, state를 변경시켜주고 싶을 때는 setState를 이용해서 간편하게 변경 시켜줄 수 있다. 여기서 state와 setState의 이름은 마음대로 지정할 수 있다.
const [time, setTime] = useState(5);
⇒ State: time = 5 (time이라는 state가 초기값으로 5를 가진다.)
setTime(6);
⇒위와 같이 setTime함수 인자에 변경될 값을 넣어주면, State: time = 6으로 변경된다.
//App.js
import { useState } from 'react';
function App() {
const [time, setTime] = useState(1);
const handleClick = () => {
setTime(time +1);
};
return (
<div>
<span>현재 시간: {time}시</span>
<button onClick={handleClick}>Update</button>
</div>
);
}
export default App;
useState와 마찬가지로 state를 생성하고 관리할 수 있게 해주는 도구
useState
가 간단한 상태 업데이트에 적합하다면,useReducer
는 상태 관리의 복잡성이 증가할 때 그 진가를 발휘합니다. 따라서, 상태 관리의 복잡성이 높아질 것으로 예상되거나 위에 언급된 상황에 해당될 때useReducer
의 사용
import React, { useReducer } from "react";
const [state, dispatch] = useReducer(reducer, initialState, init);
⇒ 한마디로 말해, 컴포넌트에서 dispatch함수에게 action을 던지면, reducer 함수가 이 action에 따라 state를 변경해준다.
const initialState = {count: 0};
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
</>
);
}
1) 플러스(+) 버튼 클릭시
2) 마이너스(-) 버튼 클릭시
게으른 초기화(lazy initialization)는 컴퓨터 프로그래밍에서 객체 생성, 값 계산, 또는 일부 기타 비용이 많이 드는 과정을 처음 필요한 시점까지 지연시키는 기법이다.
즉, 초기화 작업을 극한으로 미루다가 사용자가 필요로 할 때 진행
<기존 코드>
import { useState } from 'react';
function App() {
function initialState() {
return 0;
}
const [count, setCount] = useState(initialState());
return (
<div>
<h1>{count}</h1>
<button onClick={() => setCount(count + 1)}>카운트올려</button>
</div>
);
}
export default App;
<게으른 초기화 적용 코드>
import { useState } from 'react';
function App() {
function initialState() {
return 0;
}
const [count, setCount] = useState(() => initialState()); //수정된 부분
return (
<div>
<h1>{count}</h1>
<button onClick={() => setCount(count + 1)}>카운트올려</button>
</div>
);
}
export default App;