Remote State Management: Use Apollo Cache Instead of Custom React Context
When maintaining client state from a remote API, use the Apollo Cache instead of creating a redundant custom React context to store the state.
Reasons
- Less code to maintain.
- No redundant state (that could get out-of-sync).
- Apollo cache is publicly well-documented, so any Apollo developer could understand the code immediately (instead of having to reason through a custom implementation that might behave differently).
Examples
// Bad
const AuthContext = React.createContext(INITIAL_STATE)
const AuthProvider = ({ children }) => {
const { data, loading, error } = useQuery(CURRENT_USER_QUERY, {
fetchPolicy: 'cache-and-network',
})
const value = error ? INITIAL_STATE : { currentUser: data?.currentUser }
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
}
export const useAuthUser = (): User => {
const { currentUser, currentTeacher } = useContext(AuthContext)
const name = currentUser
? `${currentUser.firstName} ${currentUser.lastName}`
: undefined
return {
name,
}
}
// Good
export const useAuthUser = (): User => {
const { data, loading, error } = useQuery(CURRENT_USER_QUERY, {
fetchPolicy: 'cache-and-network',
})
const value = error ? INITIAL_STATE : { currentUser: data?.currentUser }
const name = currentUser
? `${currentUser.firstName} ${currentUser.lastName}`
: undefined
return {
name,
}
}
When to use custom React Context
A custom React Context is useful if the state is only relevant on the client-side (e.g. drag-and-drop context, client performance metrics, etc.). If the state is a cache of remote data, then just use the remote data cache directly.