Stack/React

[React] 상태관리(useState / useReducer) 복습

7ingout 2022. 7. 4. 09:23

상태가 변경될 때 리랜더링 됨 (다시 그려짐)

1. useState(초기값) => [ state, f ]

* 상태값 관리

const newArr = useState(초기값)

const state = newArr[0]

const setState = newArr[1]

const [ state, setState ] = useState(초기값)

setState(변경된값)

 

2. useReducer()

* 어떤 경우에 상태가 어떻게 업데이트 될건지 관리

useReducer(함수, 초기값) => [ state, 함수를 실행시키는 함수 ]

const [ state, dispatch ] = useReducer(reducer, initialstate)

dispatch({액션})

dispatch({

                type: "DELETE_USER",

                id: 10

})

const users = [

                {

                                id:1,

                                name: "a",

                                age: 30,

                                active: false               

                },

                {},

                {}               

]

function reducer(state, action) {

                switch(action.type){

                                case 'USER_DELETE':

                                return state.filter(list=> list.id !== action.id);

                                case 'USER_CREATE':

                                return state;

                                case 'USER_TOGGLE':

                                return state;

                                default:

                                return state;

                }

}