← React Beginner Questions - Set 3 Q28
React Beginner Questions - Set 3
A function that takes a component and returns a new one. It is the pre-hooks way to share behaviour, and it still appears in libraries.
function withAuth(WrappedComponent) {
return function Authenticated(props) {
const { user } = useCurrentUser();
if (!user) return <p>Please sign in</p>;
return <WrappedComponent {...props} user={user} />;
};
}
function Dashboard({ user }) {
return <h1>Welcome, {user.name}</h1>;
}
const ProtectedDashboard = withAuth(Dashboard);
// Conventions: prefix with "with", pass props through, never mutate
// the wrapped component, and set a displayName for DevTools.