What is a Hook?
Hooks were added to React in version 16.8. Hooks let you use state and other React features without writing a class.
Although states have largely replaced classes in React, there is no plan of removing classes from React.
Things you need to keep in mind while using hooks:
- You must
import
hook first - You must import it from react
- Hooks can only be called in React Function Components, meaning:
// import statements
// Can't call here
const Blogs = () => {
// Can call here
return <h1>Blogs</h1>;
};
export default Blogs;
- Hooks cannot be conditional
- Hooks cannot work in React Class Components
- Hooks can only be called at the top level of a component, meaning it can't be called from inside a block, i.e.
{}
. So, can't be called insideif
, loops or any block, example:
const Blogs = () => {
// Can call here
if (true){
// Can't call here
}
return <h1>Blogs</h1>;
};
export default Blogs;