As we all know the React Team has come up with something called React Hooks, which are an awesome feature.. yes its awesome.. trust me it is…
React 16.8.xx is shipped with React Hooks feature support in which developers can build functional components which can have own local state and props. (OH WOW)
What is a Hook?
Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don’t work inside classes — they let you use React without classes.
Let’s see what are the out of the box hooks they have for us:
📌 State Hook:
useState is a Hook (we’ll talk about what this means in a moment). We call it inside a function component to add some local state to it. React will preserve this state between re-renders.
useState returns a pair: the current state value and a function that lets you update it. You can call this function from an event handler or somewhere else. It’s similar to
this.setState in a class, except it doesn’t merge the old and new state together.
⚡️ Effect Hook:
You’ve likely performed data fetching, subscriptions, or manually changing the DOM from React components before. We call these operations “side effects” (or “effects” for short) because they can affect other components and can’t be done during rendering.
The Effect Hook,
useEffect, adds the ability to perform side effects from a function component. It serves the same purpose as
componentWillUnmount in React classes, but unified into a single API.
✌️ Rules of Hooks
- Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions.
It lets you subscribe to React context without introducing nesting. For e.g when you want to use your logged-in data deep down to some of the nested components: For e.g:
const locale = useContext(LocaleContext); const theme = useContext(ThemeContext);
useReducer hook lets you manage local state of complex components with a reducer:
Sometimes, we want to reuse some stateful logic between components. Traditionally, there were two popular solutions to this problem: higher-order components and render props. Custom Hooks let you do this, but without adding more components to your tree.
Below is a custom Hook:
The above custom hook is called useFetch which can be used as a custom hooks by calling the below method in your component
Other Useful Reads
Check out other cool React.js articles in the dedicated section at this link
If you found this article helpful, it would mean a lot if you commented it and shared to help others find it! And feel free to leave a comment below.