Splitting up components

Another way to solve conditional Hooks is to split up one component into multiple components and then conditionally render the components. For example, let's say we want to fetch user information from a database after the user logs in.

We cannot do the following, as using an if conditional could change the order of the Hooks:

function UserInfo ({ username }) {
if (username) {
const info = useFetchUserInfo(username)
return <div>{info}</div>
}
return <div>Not logged in</div>
}

Instead, we have to create a separate component for when the user is logged in, as follows:

function LoggedInUserInfo ({ username }) {
const info = useFetchUserInfo(username)
return <div>{info}</div>
}

function UserInfo ({ username }) {
if (username) {
return <LoggedInUserInfo username={username} />
}
return <div>Not logged in</div>
}

Using two separate components for the non-logged in and logged in state makes sense anyway, because we want to stick to the principle of having one functionality per component. So, usually, not being able to have conditional Hooks is not much of a limitation if we stick to best practices.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.82.23