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:
import React from "react";
import { Profile } from "./profile";
function Header({ loggedIn, handleSetLoggedIn }) {
  return (
    <>
      <Profile loggedIn={loggedIn} handleSetLoggedIn={handleSetLoggedIn} />
    </>
  );
}
function App() {
  const [loggedIn, setLoggedIn] = React.useState(false);
  const handleSetLoggedIn = () => {
    setLoggedIn(!loggedIn);
  };
  return <Header loggedIn={loggedIn} handleSetLoggedIn={handleSetLoggedIn} />;
}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
PreviousValidate using zod instead of type castingNextPrefer ternaries over Short Circuiting β&&β for React Components
Last updated
Was this helpful?