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!