Hooks were added to React in version 16.8.
Hooks allow function components to have access to state
and other React features. Hooks quite literally "hook" into React features, such as state and lifecycle methods.
Some hooks - and only* the hooks react ships (like useState and useEffect) - allow function components
to have access to state and lifecycle methods INSIDE the Chromium runtime engine.
This means that function components can now have access to state and lifecycle
methods without needing to be class components.
Because of this, class components are generally no longer needed.
What is a Hook?
Hooks are function that allow us to "hook" into React features such as state and lifecycle methods.
Hook Rules
There are 3 rules for hooks:
- Hooks can only be called inside React function components.
- Hooks can only be called at the top level of a component.
- Hooks cannot be conditional
- Hooks usually start with
use...
Custom Hooks
If you have stateful logic that needs to be reused in several components, you can build your own custom Hooks.
What hooks are available
If you check out the React documentation, a lot of hooks are available to you. Not all are feasible at a beginner level, and with each React version the amount of hooks increases. Also, a lot of plugins provide their own custom hooks after installing the library.
Importing the hooks
The syntax for importing the hooks is always similar:
import { useState, useEffect } from "react"
We always destructure the name of the hook from react