0

I am learning how to create a React reducer to be used in a React context.

Can someone explain why the instructor created the {currentUser: null} object twice? Once in the context (line 7), once as an INITIAL_STATE to be used in the reducer (lines 26 and 29). Is any of it redundant?

import { createContext, useReducer, useEffect } from "react";

import {
  onAuthStateChangedListener,
  createUserDocumentFromAuth,
} from "../utils/firebase/firebase.utils";

export const UserContext = createContext({
  currentUser: null,
  setCurrentUser: () => null,
});

export const USER_ACTION_TYPES = {
  SET_CURRENT_USER: "SET_CURRENT_USER",
};

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

  switch (type) {
    case "SET_CURRENT_USER":
      return {
        ...state,
        currentUser: payload,
      };
    default:
      throw new Error(`Unhandled type ${type} in userReducer`);
  }
};

const INITIAL_STATE = {
  currentUser: null,
};

export const UserProvider = ({ children }) => {
  const [state, dispatch] = useReducer(userReducer, INITIAL_STATE);
  const { currentUser } = state;

  const setCurrentUser = (user) => {
    dispatch({ type: USER_ACTION_TYPES.SET_CURRENT_USER, payload: user });
  };

  const value = { currentUser, setCurrentUser };

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

      setCurrentUser(user);
    });
    return unsubscribe;
  }, []);

  return <UserContext.Provider value={value}>{children}</UserContext.Provider>;
};

Thanks!

chu-js
  • 181
  • 7

1 Answers1

0

No none is redundant. The currentUser property in the INITIAL_STATE object is the initial state for your useReducer hook while the other currentUser is the initial state for your useContext hook.

  • May I know if the initial states of the useReducer and createContext hooks refer to the same object? Since they are created separate, it seems like they are different objects. If they are different objects, which object are the other components in the app referencing when they call currentUser? Thanks. – chu-js Nov 25 '22 at 16:43