Search
K
Comment on page

Prefer Composition over Prop Drilling

Instead of relying on prop drilling, let's try to take advantage of react children feature. Having this as an example:
1
import React from "react";
2
import { Profile } from "./profile";
3
4
function Header({ loggedIn, handleSetLoggedIn }) {
5
return (
6
<>
7
<Profile loggedIn={loggedIn} handleSetLoggedIn={handleSetLoggedIn} />
8
</>
9
);
10
}
11
12
function App() {
13
const [loggedIn, setLoggedIn] = React.useState(false);
14
15
const handleSetLoggedIn = () => {
16
setLoggedIn(!loggedIn);
17
};
18
19
return <Header loggedIn={loggedIn} handleSetLoggedIn={handleSetLoggedIn} />;
20
}
Instead of "drilling props" all the way down, focus having everything as top level as possible:
import React from "react";
import { Profile } from "./profile";
function Header({ children }) {
return (
<>
{children}
</>
);
}
function App() {
const [loggedIn, setLoggedIn] = React.useState(false);
const handleSetLoggedIn = () => {
setLoggedIn(!loggedIn);
};
return (
<Header>
<Profile loggedIn={loggedIn} handleSetLoggedIn={handleSetLoggedIn} />
</Header>
);
}

More sources on this topic