Skip to main content

React Hooks Conditionally

This example highlights an important rule in React: hooks cannot be used conditionally.

If you try to use a hook like useState inside a conditional statement, React will throw an error.

This is because React relies on the order of hooks to be consistent across renders. To avoid this, you can restructure your component to handle conditional rendering without breaking this rule. Instead of returning different parts of the component based on a condition, the whole rendering logic can be placed inside a single return statement using a ternary operator.

// import { useState } from "react";

const Second = ({ id }) => {
// conditional rendering
if (!id) {
return "There is no id!";
}

// hooks cannot be used here - hooks cannot be used conditionally
// const [state, setState] = useState(0);

return <section>Something {id}</section>;
};

// instead of the example above, everything can be done in one return statement
/*
return (
<section>
{!id
? "There is no id!"
: `Something ${id}`
}
</section>
)
*/

export default Second;