Stack/React

[React] useState / useReducer / Context API 복습

7ingout 2022. 6. 29. 09:50

리액트 - 싱글페이지 애플리케이션 / 한 개의 페이지로 이루어진 애플리케이션

 

상태

useState

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

useState(10) => return [ state, f ]   // state(상태)는 f로만 관리 가능

 

const stateArr =  useState(10);

const state = stateArr[0];

const setState = stateArr[1];

=

const [ state, setState ] = useState(10);   // 구조분해할당

 

 

 

useReducer

function reducer(state, action) {

        switch(action.type){

                case "CHANGE_USER":

                return {

                    ...state,

                    users: state.users.map(user=> user.id !== action.id)

                }               

        }

}

useReducer(함수, 초기값) => [ state, dispatch ]

dispatch(액션객체) => reducer를 실행

dispatch({

                type: "CHANGE_USER",

                id: 10,

})

 

 

 

props / Context API

App 컴포넌트(상태) -> Users 컴포넌트 -> UserList 컴포넌트

function onelete() {

                상태에서 유저 한명만 제거하는 함수

}

<Users usersArr = {usersArr}>

<UserList user = {user} />

<button> 누를 때 위의 함수가 실행되어야 함, 그러나 <button onClick = {onDelete}> 이렇게 해도 실행 X

 

프로젝트 안에서 전역적으로 사용할 수 있는 값을 관리

createContext(null); => context를 return -> 컴포넌트

const MyContext = createContext(null);

 

<MyContext.Provider value = "green">

                <App>

                                <Main/>

                </App>

</MyContext.Provider>

context값을 사용

 

useContext(컨텍스트 이름)

ex> const abc = useContext(MyContext) => green을 반환