What is the provider pattern in React and how does it relate to the Context API?
Short answer
The provider pattern wraps a piece of your app in a component that supplies shared data and functions to everything inside it, usually built using the Context API.
Advertisement
AModel answer
The provider pattern wraps a piece of your app in a component that supplies shared data and functions to everything inside it, usually built using the Context API. This keeps related state and logic organized in one place, and any component nested inside the provider can access it without prop drilling.
function AuthProvider({ children }) {
const [user, setUser] = useState(null);
const login = (userData) => setUser(userData);
const logout = () => setUser(null);
return (
<AuthContext.Provider value={{ user, login, logout }}>
{children}
</AuthContext.Provider>
);
}Real-world example
An app wraps its entire component tree in an AuthProvider, giving every page easy access to the current user, plus login and logout functions, without passing any of that data manually through props.
Likely follow-ups
- How is the provider pattern different from just using props to pass data down?
- When would you use multiple providers together, like both an AuthProvider and a ThemeProvider?
Related topics