state란 컴포넌트가 가질 수 있는 상태입니다.
const [state, setState] = useState(initialState);
useState는 배열 구조 분해 할당을 사용하여 배열을 반환합니다.
첫 번째 값은 상태 유지 값이고, 두 번째 요소는 그 값을 갱신하는 함수입니다.
최초로 렌더링을 하는 동안, 반환된 state(state)는 첫 번째 전달된 인자(initialState)의 값과 같습니다.
setState(newStates)
setState 함수는 state를 갱신할 때 사용합니다. 새 state 값을 받아 컴포넌트 리렌더링을 큐에 등록합니다.
useState() Hook은 컴포넌트 함수 안에서 직접 호출돼야 합니다.
함수 밖이나 중첩 함수 안에서 호출될 수 없습니다.
import React, { useState } from 'react'
// React Hook "useState" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function react-hooks/rules-of-hooks
// 컴포넌트 밖에서 호출할 경우(컴포넌트에서 사용해야 된다는 내용)
const [wrong, setWrong] = useState("");
const App = () => {
const [expenses, setExpenses] = useState(DUMMY_EXPENSES);
const addExpenseHandler = (expense) => {
// React Hook "useState" is called in function "addExpenseHandler" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter. React Hook names must start with the word "use" react-hooks/rules-of-hooks
// 중첩 함수 안에서 호출할 경우(addExpenseHandler가 컴포넌트 맞냐는 내용)
const [wrong, setWrong] = useState("");
setExpenses((prevExpenses) => {
return [expense, ...prevExpenses];
});
};
return (
<div>
<NewExpense onAddExpense={addExpenseHandler} />
<Expenses items={expenses}/>
</div>
);
}