React Hooks



What is React Hooks ?

Hooks are a new feature that is introduced to the React Version 16.8. It allows to use state and other React feature without writing a class. 

Hooks do not work inside classes. It is backward-compatible ( no breaking changes )

When to use a Hooks ?

After writing a function component, state can be added to it using a Hook inside an existing function component.

Rules of Hooks

Hooks are similar to JavaScript functions, but there are 2 rules that needs to followed when using Hooks.

1. Only call Hooks at the top level

Do not call Hooks inside loops, conditions, or nested functions. Hooks should always be used at the top level of the React functions. This rule ensures that Hooks are called in the same order each time a components renders.

2. Only call Hooks from React functions

Hooks cannot be called from regular JavaScript functions. Instead, Hooks can be called from React function components. Hooks can also be called from custom Hooks.

Pre-requisites for React Hooks

  1. Node version 6 or above
  2. NPM version 5.2 or above
  3. Create-react-app tool for running the React App

React Hooks Installation

To use React Hooks, we need to run the following commands:

  1. $ npm install react@16.8.0-alpha.1 --save  
  2. $ npm install react-dom@16.8.0-alpha.1 --save  

The above command will install the latest React and React-DOM alpha versions which support React Hooks. Make sure the package.json file lists the React and React-DOM dependencies as given below.

  1. "react""^16.8.0-alpha.1",  
  2. "react-dom""^16.8.0-alpha.1",  


Comments