Context
Context
Instead of prop drilling we can use context. This is a method of passing down data through several components without the need to pass it down manually at each "level". There are quite a few libraries which try achieve the same thing, for example Redux and MobX. Examples of good use cases for Context would be global themes for styling, or a user object which will most likely be needed throughout an app.
We can create a user object and pass that value into Context. Other components can get this user object easily by doing the following hook with a User example:
const user = useContext(UserContext)To use something like this, we could do the following:
import { useContext, useState } from 'react'
const UserContext = React.createContext({})
export const UserProvider = UserContext.Provider
const [user, setUser] = useState({
name: 'Jeff',
hobby: 'Sleeping',
age: '24',
})
function ComponentWithContext() {
const user = useContext(UserContext)
return <p>Hello, {user.name}</p>
}
// render ...
<UserContext.Provider value={user}>
<ComponentWithContext />
</UserContext.Provider>
Hello, Jeff
Typically each "piece" of context would have its own provider. For example you'd have a UserContext and ThemeContext.