Rules are meant to be broken - The use exception
TLDR
use function is part of the React API and not a Hook
"The first rule of React Hooks is: You don't call hooks conditionally… unless it's the use hook!"
If you've been in React development for any time, you've probably had the Rules of Hooks burned into your brain:
1. Only call Hooks at the top level
2. Only call Hooks from React functions
These rules exist for good reason - they ensure that hook state is correctly preserved between renders. Breaking them typically leads to bugs that are difficult to track down.
But in a surprising twist, the use hook breaks the mold. Unlike every other hook in React, use can be called conditionally - something that would be illegal with any other hook!
This represents a fundamental shift in React's programming model. React has made data fetching much more natural and intuitive by allowing use to be called conditionally.
Learn more about this at:
- Official docs: https://react.dev/reference/react/use#usage
- Simple demo: https://use-react-api-vite-demo.netlify.app/
#ReactJS #WebDevelopment #Frontend #JavaScript #ReactHooks