React) state updating

이해원·2022년 1월 6일
0

시작하기

목록 보기
23/27

useState hook 얘기할때 같이 얘기해었지만 따로 간단하게 다시 정리!

일반적인 방법처럼 state를 업데이트하는것(state가 바뀜)은 아주아주 정확한 방법은아니다.

=> 일반적인 방법

const App = () => {
	const [expenses, setExpenses] = useState(DUMMY_EXPENSES);
    
    const addExpenseHandler = (newExpense) => {
		setExpenses ([ newExpense , ...expenses ]);
	};
};

=> 바로 이전 state에서 state updating을 하는 더 깔끔하고 확실한 방법

const App = () => {
    const [expenses,setExpenses]=useState(DUMMY_EXPENSES);

  const addExpenseHandler = expense => {
    setExpenses(prevExpenses => {
      return [expense,...prevExpenses]
    });
  };

특히나 state를 바꾸는데 그 전 state 에 영향을 받는다면 state를 업데이트 하는 특별한형태의 function 을 써야한다.

So it would be passed a function as argument to this state updating function and that function will automatically receive the latest state snapshot.

So here we would then get our previous expenses automatically by React. And we would return our new array our previous expenses with that spread operator.

profile
미어캣입니당

0개의 댓글