wasAsked.

explain prop drilling

PwC · Full Stack Developer · technical

Published

Year not specified · React

Community answers

Posted by wasAsked editorial collection

Prop drilling is passing data through several layers of components that do not need it themselves, just so a deeply nested component can receive it. Example function App() { const [user, setUser] = useState<User | null>(null); return <Layout user={user} />; } function Layout({ user }: { user: User | null }) { return <Sidebar user={user} />; // Layout does not use user } function Sidebar({ user }: { user: User | null }) { return <UserMenu user={user} />; // Sidebar does not use user either } function UserMenu({ user }: { user: User | null }) { return <span>{user?.name}</span>; // only this component needs it } Problems - Intermediate components get extra props they do not care about, making them harder to read and reuse. - Refactoring is painful: renaming or adding a prop touches every layer. - Unnecessary re-renders of intermediate components. Prop drilling through one or two levels is perfectly fine and explicit. It becomes a problem with deep trees or many shared values. Solutions 1. Component composition (often the simplest) Pass already-built elements as children or slots, so intermediate components do not need the data: <Layout sidebar={<Sidebar menu={<UserMenu user={user} />} />} /> 2. Context API for widely needed data const UserContext = createContext<User | null>(null); <UserContext.Provider value={user}><Layout /></UserContext.Provider> function UserMenu() { const user = useContext(UserContext); return <span>{user?.name}</span>; } Best for global, rarely changing data: authenticated user, theme, locale, feature flags. 3. State management libraries Redux Toolkit, Zustand or Jotai for complex shared state with frequent updates; components subscribe to just the slices they need. 4. Server-state libraries TanStack Query or RTK Query: any component can call useQuery(['user']) and get cached data without passing it down. 5. Co-locate state Move state down to the component that actually uses it, or to the nearest common parent of the components that need it. Choosing: use composition and co-location first, Context for app-wide settings, and dedicated libraries for complex or server state.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics