Hands-on practice for this lecture. Write the code, see it run, understand the pattern.
Exercise 1 of 1
Three questions on container components: what cloneElement does, how many network requests fire, and why display components should never fetch their own data.
Question 1
const CurrentUserLoader = ({ children }) => {
const [user, setUser] = useState(null);
useEffect(() => {
(async () => {
const res = await axios.get('/current-user');
setUser(res.data);
})();
}, []);
return (
<>
{React.Children.map(children, child =>
React.isValidElement(child)
? React.cloneElement(child, { user })
: child
)}
</>
);
};What does React.cloneElement(child, { user }) do?
Question 2
<CurrentUserLoader> <UserProfile /> <UserStats /> </CurrentUserLoader>
How many network requests does CurrentUserLoader make?
Question 3
const UserProfile = ({ user }) => (
<div>{user?.name}</div>
);Should UserProfile import axios or call useEffect to fetch its own data?
0 / 3 answered