What Are ReactJS Hooks? Explained
Table of Contents
- What are Hooks in ReactJS?
- When to use React Hooks?
- Rules of Hooks in React
- Test your knowledge with a quick quiz!
- How to install React Hooks?
What are Hooks in ReactJS?
ReactJS Hooks were first introduced in the React 16.8 version. They give you access to use state and other React features without the use of class.
Taken literally, hooks in React are the functions which "hook into" React state and lifecycle features from function components. They do not work inside classes. This implies that when hooks are present, we do need class components.
And if you are thinking that they might replace classes, you are wrong because classes form an integral part of React and there are no plans of removing them from React.
When to use React Hooks?
All this while you have been adding state to a function component by converting it to a class. With hooks, you can add a state inside a function component without converting it to a class.
Rules of Hooks in React
Hooks to be called only from React function components
Hooks to be called only at the top level
It is not possible to call Hooks inside loops, nested functions, or conditions. You should always call them at the top level of a React component.
Hooks cannot be conditional
Calling the Hooks conditionally can change the order of the Hooks being rendered and mess up the entire Hooks system.
A few prerequisites to use React Hooks are:
Having Node version 6 or above
Having NPM version 5.2 or above
Having the Create-react-app tool for running the React App
Test your knowledge with a quick quiz!
Can we use hooks in React Class Based Components?
Select the correct answer
How to install React Hooks?
Run the following command to install Hooks.