- Hooks are the new feature added in the React 16.8
- It lets you use state and different React functions without writing a class.
- React concepts does not replace your knowledge.
- Inside classes do not work.
- Hooks are the functions that “hook into” React state and lifecycle features from the function.
For example:
[pastacode lang=”markup” manual=”import%20React%2C%20%7B%20useState%20%7D%20from%20%22react%22%3B%0Aimport%20ReactDOM%20from%20%22react-dom%22%3B%0A%0Afunction%20FavoriteColor()%20%7B%0A%20%20const%20%5Bcolor%2C%20setColor%5D%20%3D%20useState(%22blue%22)%3B%0A%0A%20%20return%20(%0A%20%20%20%20%3C%3E%0A%20%20%20%20%20%20%3Ch1%3EMy%20favorite%20color%20is%20%7Bcolor%7D!%3C%2Fh1%3E%0A%20%20%20%20%20%20%3Cbutton%0A%20%20%20%20%20%20%20%20type%3D%22button%22%0A%20%20%20%20%20%20%20%20onClick%3D%7B()%20%3D%3E%20setColor(%22yellow%22)%7D%0A%20%20%20%20%20%20%3EYellow%3C%2Fbutton%3E%0A%20%20%20%20%20%20%3Cbutton%0A%20%20%20%20%20%20%20%20type%3D%22button%22%0A%20%20%20%20%20%20%20%20onClick%3D%7B()%20%3D%3E%20setColor(%22blue%22)%7D%0A%20%20%20%20%20%20%3EBlue%3C%2Fbutton%3E%0A%20%20%20%20%20%20%3Cbutton%0A%20%20%20%20%20%20%20%20type%3D%22button%22%0A%20%20%20%20%20%20%20%20onClick%3D%7B()%20%3D%3E%20setColor(%22orange%22)%7D%0A%20%20%20%20%20%20%3EOrange%3C%2Fbutton%3E%0A%20%20%20%20%20%20%3Cbutton%0A%20%20%20%20%20%20%20%20type%3D%22button%22%0A%20%20%20%20%20%20%20%20onClick%3D%7B()%20%3D%3E%20setColor(%22violet%22)%7D%0A%20%20%20%20%20%20%3EViolet%3C%2Fbutton%3E%0A%20%20%20%20%3C%2F%3E%0A%20%20)%3B%0A%7D%0A%0AReactDOM.render(%3CFavoriteColor%20%2F%3E%2C%20document.getElementById(‘root’))%3B%0A” message=”” highlight=”” provider=”manual”/]We must import Hooks from react. The useState is used to track the application state.
Rules of Hooks:
- Call Hooks from React function components.
- Call Hooks from Top level.
- It cannot be conditional.
