codedamn logo
codedamn

What is Hooks in React.js & types of Hooks in React.js

  • Vishnupriya's profile image
    Vishnupriya
    Team codedamn
What is Hooks in React.js & types of Hooks in React.js

Hey readers, In this blog we will learn about what are hooks in React js and why is it used. If you are new to React js, I would recommend you to go through its fundamentals and working of React, you can find it on codedamn. If you are aware of it, keep reading. 

Hooks in React js

Hooks were introduced in React version 16.8. It allows developers to use the state and other features of React without even writing a class. These are functions that “hook” into the state and lifecycle features of components in React. It does not work inside any classes.

It does not contain any breaking changes, which means it has backward compatibility. Also, it works well with react js without even changing anything.

When should developers use Hooks with React js?

If you know React then you know that while writing a functional component, if developers want to add some state to it, it was been done by converting functional component to class component. This is why hooks were introduced to solve this problem. Now we can add the state by just using hooks in the existing functional component.

Rules of using hooks

Hooks are just like JavaScript’s function but there are certain rules to be followed while using hooks. These rules ensure that all the logic of components is visible in the source code.

  • Call hooks only at the top-level- This means that we should never call hooks inside a loop, conditions, or even nested functions and should be only called in the React functions. This maintains the order of components whenever it is rendered.
  • Call hooks only from a React js function- hooks cannot be called using regular JavaScript function instead it can be called from React function components. React hooks can also be called custom hooks.

Here are some prerequisites for hooks

  1. Node version should be 6 or above
  2. Npm version should be 5.2 and above
  3. Create-react-app tool for running React App

Installing React hooks

To use hooks in your React application, run the command given below

npm install react@16.8.0-alpha.1 –save  

npm install react-dom@16.8.0-alpha.1 –save  

The command given above will install the latest version of React and React-DOM alpha version which supports hooks. To see if it’s installed properly or not, go to the package.json file in your folder and see these two dependencies are there or not. 

Hook state

These are the new ways of initializing a state in React app. It uses useState() functional component for retrieving and setting the state. To understand it better, consider the following example.

Create a file App.js

import React, { useState } from 'react'; 
function CountApp() { 
// Declare a new state variable, which we'll call "count" 
const [count, setCount] = useState(0); 
return ( 
<div> 
<p>You clicked {count} times! Welcome to codedamn.</p> 
<button onClick={() => setCount(count + 1)}> 
Click me 
</button> 
</div> 
); 
} 
export default CountApp; 

In the above example, the useState hook needs to be called inside a functional component so as to add a local state to it.  It returns a pair where the initial one is the current state and the second one is the function that allows us to update the state. After this is done, developers can call this function from anywhere like an event handler, etc. This useState is similar to this.setState of the class component.

Hooks effect

It allows us to perform side actions in the functional component. It does not use lifecycle methods present in-class components. Hook effects are similar to componentDidMount(), componentDidUpdate() and componentWillUnmount() lifecycle methods. We have covered it in detail in React js lifecycle blog on codedamn so do check it out. Consider the below example to understand Hook effects better.

It is similar to the previous example except, in this case, the document title gets updated with a message and number of clicks.

import React, { useState, useEffect } from 'react'; 
function CounterExample() { 
const [count, setCount] = useState(0); 

// Similar to componentDidMount and componentDidUpdate: 
useEffect(() => { 
// Update the document title using the browser API 
document.title = `You clicked ${count} times`; 
}); 
return ( 
<div> 
<p>You clicked {count} times</p> 
<button onClick={() => setCount(count + 1)}> 
Click me 
</button> 
</div> 
); 
} 
export default CounterExample; 

Custom Hooks

These are similar to the Javascript functions. Its name starts with ‘use’ which can call other hooks. The reason for using custom hooks is that they allow developers to extract a component’s logic into reusable functions.

import React, { useState, useEffect } from 'react'; 
const useDocumentTitle = title => { 
useEffect(() => { 
document.title = title; 
}, [title]) 
} 
function CustomCounter() { 
const [count, setCount] = useState(0); 
const incrementCount = () => setCount(count + 1); 
useDocumentTitle(`You clicked ${count} times`); 
// useEffect(() => { 
// document.title = `You clicked ${count} times` 
// }); 
return ( 
<div> 
<p>You clicked {count} times</p> 
<button onClick={incrementCount}>Click me</button> 
</div> 
) 
} 
export default CustomCounter; 

Conclusion 

These were some of the basic hooks in React. Do let us know if you have any queries in the comment box and check out courses on codedamn if you want to learn development and join our community codedamn.

User avatar