Use Of Hooks

Posted By :Vikrant Kumar |31st March 2022

 

What is Hooks

For every frontend developer, managing user data is one of the most primal task. React introducing the Hooks API in thier release 16.8, They let you use state and other React feature without writing a class.

Before React hooks developer's were required to write class components in order to take advantage of certain react features. But now, React Hooks provides a more ergonomic way to build components because we can use statefull logic without changing our component hierarchy.

 

 

Rules of Hooks

Hooks are javascript functions, but you need to follow two rules when using them. We provide a linter plugin to enforce these rules automatically.

 

Only call Hooks at the Top Level

Don't call Hooks inside loops, conditions, or nested function. Always use Hooks at the top level of your React function, before any early returns.By following this rule, you ensure that Hooks are called in the same order each time a component render.That's what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.

 

Only call Hooks from React Function

Don't call Hooks from regular javascript function. Instead, you can:

  • Call Hooks from React function components.
  • Call Hooks from custom Hooks.

 

Most used Hooks

 

1) useState

2) useEffect

3) useContext

4) useRef

5) useReducer

 

 

1) useState : 

It is the most important and often used hooks. The purpose of this hook to handle reactive data, any data that changes in the application is called state, when any of the data changes, React re-renders the UI.

 

import React, { useState } from 'react';

const [count, setCount] = useState(0);


 

 

2) useEffect : 

It allows us to implement all of the lifecycle hooks from within a single function API. The Effect Hook, useEffect adds the ablility to perform side effect from a function component. It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in react classes, but unified into a single API.

 

import React, { useState, useEffect } from 'react';

// This will run when the component mounts and anytime the stateful data changes.

useEffect(()=> {

alert('Hello world.')

});

 

// This will run, when the component is first initialized.

useEffect(() => {

alert('Hello world.');

},[]);

 

// This will run only when count (dependencies) state changes

useEffect(() => {

alert('Hello world.');

},[count, dependencies1, dependencies2]);

 

 

// This will run only when the component is destroyed or before the component is removed from UI.

useEffect(()=>{

alert('Hello world.');

// called as cleanup function

return ()=> alert('Bye component');

});

 

 

3) useContext : 

This hooks allows us to work with React's Context API, which itself a mechanism to allow us to share data within it's component tree without passing through props. It basically removes prop-drilling

Accepts a context object (the value returned from React.createContext) and returns the current context value for that context. The current context value is determined by the value prop of the nearest <MyContext.Provider> above the calling component in the tree.

 

import React, { useContext } from 'react';

const themes  = {

light : {

foreground : '#000000',

background : '#eeeeee'

},

dark : {

foreground : '#ffffff',

background : '#222222'

}


const ThemeContext = React.createContext(theme.light);


function App(){

<ThemeContext.Provider value={themes.dark}>

<Toolbar/>

</ThemeContext.Provider>

}


function Toolbar(props){

return (

<div>

<ThemeButton/>

</div>

)};


function ThemeButton(){

const theme = useContext(ThemeContext);

return (

<button style={{background : theme.background, color: theme.foreground}}>

Button

</button>

)};

 

4) useRef : 

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.but the difference is, it dosn't trigger a re-render when the value changes.

 

import React, { useRef } from 'react';


function App(){

const btn = useRef(null);

const handleBtn = ()=> btn.current.click();

return (

<button ref={btn} onChange={handleBtn}> Button </button>

)};

 

 

4) useReducer :

It does very similiar to setState, It's a different way to manage state using Redux Pattern. Instead of updating the state directly, we dispatch actrions, that go to a reducer function, and this function figure out, how to compute the next state.

 

import React, { useReducer } from 'react';


function reducer(initialState, dispatch){

switch (action.type){

case 'increment' : 

return state + 1;


case 'decrement' : 

return state - 1;

default : 

throw new Error();

}};


function useReducer(){

const [state, dispatch] = useReducer(reducer, 0);

return (

<>

count : {state}

<button onClick = {()=> dispatch({type : 'decrement'})} - </button>

<button onClick = {()=> dispatch({type : 'increment'})} + </button>

</>

)};

 


About Author

Vikrant Kumar

Vikrant is a skilled and knowledgeable back-end developer with extensive experience in the industry. He is proficient in various programming languages, such as NodeJS, ExpressJS, MongoDB, React, Angular, and JavaScript. Vikrant has worked on several challenging projects, including Konfer, and has a deep understanding of development principles. He is committed to expanding his knowledge of new technologies and constantly improving his skills to deliver exceptional software products.

Request For Proposal

[contact-form-7 404 "Not Found"]

Ready to innovate ? Let's get in touch

Chat With Us