Some blog articles split up the context into two seperate update and state context when working with React Context. I am wondering whether this really increases the performance or can lead to reduced render cycles.
So the final solution will have:
- two different context objects
- two different hooks for 1.) accessing the state and 2.) modifying the state
- two seperate providers (wrapped into one single one like in
AuthProvider
)
Solution splitting up Update and State Context:
const authContext = React.createContext<AuthUser | null | undefined>(undefined)
const authUpdateContext = React.createContext<Dispatch<SetStateAction<AuthUser | null>> | null>(null)
export function useAuth() {
const authUser = React.useContext(authContext);
if (authUser === undefined) throw new Error(`useAuth must be used within a ContextAuthProvider`);
return authUser;
}
export const useAuthUpdate = () => {
const setAuthUser = React.useContext(authUpdateContext);
if (!setAuthUser) throw new Error(`useAuthUpdate must be used within a AuthProvider`);
return setAuthuser;
}
export const AuthProvider: React.FC = ({children}) => {
const [authUser, setAuthUser] = useState<AuthUser | null>(null)
return (
<authUpdateContext.Provider value={setAuthUser}>
<authContext.Provider value={authUser}>
{children}
</authContext.Provider>
</authUpdateContext.Provider>
)
}
// Usage only in components where needed (one of those two or both combined)
const authUpdate = useAuthUpdate()
const auth = useAuth()