<aside> 💡 React의 꽃(?)이라고 생각하는 상태관리에 대해 알아보자
</aside>
react를 이용한 프로젝트를 진행하다보면, 하나의 state에 여러가지 키값을 넣고 obj로 관리할때가 많다. 이럴때, 만약에 예전 state를 직접적으로 이용하여, setState를 하게 되면, outdated data를 가지고 update하게 되는 불상사가 생길 수 있으므로, 아래와 같은 방식으로 사용하도록 하자.
이렇게 arrowFuntion과 prevState를 이용해 정확하게 latestdate를 이용하여 상태관리를 할 수 있다.
const [test, setTest] = useState({apple: "red", burger: "you will be fat"})
//정확한 사용법(burger의 값만 바꾸고 싶을때)
setTest((prevState) => {...prevState, burger: "is delicious"})
//잘못된 방법(작동은 될수 있지만, 오류발생 가능성 높아진다.)
setTest({...prevState, burger:"is my life"})
if setState is depend on previous state, we can't guarantee other state is updated due to react-scheduling. in this case, we can use arrow function to guarantee updated state. but if the state is depend on other state???
const [test, setTest] = useState('');
const [updated, setUpdated] = useState(1);
// this way can't guarantee the state is latest one.
setTest(test+1);
// so we use arrow function.
setTest((prevState) => prevState + 1);
//but if 'test' state is depend on update state??
// we can't use prevState cuz it is not depend on prev test state.
// in this case, we need to use useEffect
// there is other way to guarantee latest state in class component, there is no other way in function component.
useEffect(() => {
setTest(update + 1)
}, [update])
// if we do like above, we can guarantee the update state that is used in setTest is the latest one.
https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately