← React Beginner Questions - Set 7 Q65

How can you avoid prop drilling in React?

React Beginner Questions - Set 7

Example

const UserContext = createContext(null);

function App({ user }) {
  return (
    <UserContext.Provider value={user}>
      <Layout><Sidebar><Avatar /></Sidebar></Layout>
    </UserContext.Provider>
  );
}

function Avatar() {
  const user = useContext(UserContext);   // no props at all
  return <img src={user.avatar} alt={user.name} />;
}

What to notice

← Back to the question list