Performance: User context in components
This affects how quickly components can access and render user-specific data, impacting interaction responsiveness and initial content load.
import { createContext, useContext } from 'react'; const UserContext = createContext(null); <UserContext.Provider value={user}> <ComponentA /> <ComponentB /> <ComponentC /> </UserContext.Provider>
const user = fetchUser();
<ComponentA user={user} />
<ComponentB user={user} />
<ComponentC user={user} />| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Prop drilling user data | Multiple prop updates | Multiple reflows per component | Higher paint cost due to repeated updates | [X] Bad |
| Using user context provider | Single context update | Single reflow for user data | Lower paint cost with fewer updates | [OK] Good |
createContext in Astro components?createContext doescreateContext creates a shared space to hold data accessible by many components.useContext is the hook used to access context data inside components.const user = useContext(UserContext); to get the user data.const UserContext = createContext();
function UserProfile() {
const user = useContext(UserContext);
return <div>Hello, {user.name}!</div>;
}
function App() {
return (
<UserContext.Provider value={{ name: 'Alice' }}>
<UserProfile />
</UserContext.Provider>
);
}UserContext.Provider wraps UserProfile and provides { name: 'Alice' } as context.UserProfile reads the context with useContext(UserContext) and accesses user.name.const UserContext = createContext();
function UserProfile() {
const user = useContext(UserContext);
return <div>Welcome, {user.name}!</div>;
}
function App() {
return (
<UserProfile />
);
}UserProfile component uses useContext(UserContext) but is not inside a UserContext.Provider.user.name will cause an error or be undefined.name and role to nested components. Which code correctly sets up the context and accesses both values inside a child component?const UserContext = createContext();
function UserProvider({ children }) {
return (
<UserContext.Provider value={{ name: 'Bob', role: 'admin' }}>
{children}
</UserContext.Provider>
);
}
function Dashboard() {
const user = useContext(UserContext);
return <div>User: {user.name}, Role: {user.role}</div>;
}'s UserProvider passes { name: 'Bob', role: 'admin' } as value, providing both properties.useContext(UserContext) and accesses user.name and user.role correctly.Pass the test and this pattern moves unknown