[Udemy] userContext => Redux로 리팩토링하기

박세화·2023년 7월 24일

React JS

목록 보기
11/22

App.js

const App = () => {
  const dispatch = useDispatch();

  useEffect(() => {
    const unsubscribe = onAuthStateChangedListener((user) => {
      if (user) {
        createUserDocumentFromAuth(user);
      }
      dispatch(setCurrentUser(user));
    });

    return unsubscribe;
  }, []);

user.action.js

export const setCurrentUser = (user) => 
    createAction(USER_ACTION_TYPES.SET_CURRENT_USER, user);

reducer.utils.js

const createAction = (type, payload) => ({ type, payload })

user.reducer.js

const INITIAL_STATE = {
  currentUser: null,
};

export const userReducer = (state = INITIAL_STATE, action) => {
  const { type, payload } = action;

  switch (type) {
    case USER_ACTION_TYPES.SET_CURRENT_USER:
      return {
        ...state,
        currentUser: payload,
      };
    default:
      return state;
  }
};
  • 여기까지가 dispatch 를 통해 currentUser를 업데이트하는 과정

import { selectCurrentUser } from "../../store/user/user.selector";

const Nav = () => {
  const currentUser = useSelector(selectCurrentUser);
  ...

user.selector.js

export const selectCurrentUser = (state) => state.user.currentUser;
  • useSelector hook을 사용하여 store내부(store => user => currentUser)의 값에 접근할 수 있다.

2개의 댓글

comment-user-thumbnail
2023년 7월 24일

유익한 글이었습니다.

1개의 답글