Hooks In ReactJS

hooks in reactjs

Introduction

In the further versions of ReactJS, the performance of functional components is greater than class components. So, developers prefer to use functional components. But in functional components, we cannot have the state of a function. The main purpose of using hooks in ReactJS is to provide state to the functional component. Hooks let you use a greater set of React’s capabilities without relying on classes. React components have traditionally been function-like in nature. Hooks in ReactJS fully embrace this functional approach while retaining React’s practical nature.

What is Hook

Hooks in ReactJS are a new feature addition in ReactJS version 16.8, which allows you to use features of class components without writing class. Features like state, context, side effects, and lifecycle methods of a component. Hooks in ReactJS are also useful in extracting stateful logic from components. We can test and reuse the logic independently. Hooks provide a way to reuse stateful logic without altering the structure of your components. This simplifies the sharing of states across multiple components. So before seeing the different types of hooks, we will first discuss some rules for using hooks in React.

Rules to use Hooks in ReactJS

  • Always call hooks at the top level of the functional component. Never call hooks inside conditions, nested functions, or loops.
  • Always call hooks from functional components of react. Never call it from the regular JavaScript functions.

useState Hook

The useState hook is one of the most important hooks in React. The useState hook enables you to add a state to your functional component. Suppose we have a functional component in our code base, and you later realize that you need to maintain the state for the component instead of converting it into a class component; you can simply use the useState hook to maintain the state inside the functional component.

Syntax of useState Hook

const [state, setState] = useState(initialState);

Parameters

  • state: The value of the current state.
  • setState: Used to update the state.
  • initialState: Initial value of the state.

We will take an example and will demonstrate how the useState hook works.

Example

To understand this example, first, we will create basic react app using the following command. The following example will be of a simple counter application.

“npx create-react-app reactapp”

Now edit the App.js page as follows:

import './App.css';
import React, {useState} from 'react';

function App() {
  
  const [value, setValue] = useState(0);

  function increase(){
    setValue(value => value+1);    
  }

  function decrease(){
    setValue(value => value-1);    
  }

  return (
    <div className="App">
      <br></br><br></br>
      <button onClick={increase}>Increase by 1</button>
      <br></br><br></br>
      {value}
      <br></br><br></br>
      <button onClick={decrease}>Decrease by 1</button>
    </div>
  );
}

export default App;

Output

useState hook in reactjs

Explanation

We use useState by importing it from ‘react’ (refer to the first line of code). So when we call the useState hook, it declares a state variable. In our code, we named the state variable as ‘value.’ We have to pass some initial value of the state variable as an argument to the useState hook. In the above code, we have passed 0 as the initial value of the state variable. The useState returns a pair of values. The first value is the current state of the state variable, and the second is the function that updates the state variable.

Whenever we need to update the state variable, we need to use a function that is returned by the useState hook. In the above code, we have named it ‘setValue.’ We call the increase()method and update the state variable using the setValue function with the click of increment button, similarly for the decrement button.

Note: We can also use multiple state variables for a single functional component. Following is a small example where we will be using two state variables inside a single functional component.

Example

import './App.css';
import React, {useState} from 'react';

function App() {

  const [value1, setValue1] = useState(0);
  const [value2, setValue2] = useState(0);

  function increase1(){
    setValue1(value1 => value1+1);    
  }
  function decrease1(){
    setValue1(value1 => value1-1);    
  }

  function increase2(){
    setValue2(value2 => value2+2);    
  }
  function decrease2(){
    setValue2(value2 => value2-2);    
  }

  return (
    <div className="App">
        <table>
          <tr>
            <th><button onClick={increase1}>Value +1</button></th>
            <th>{value1}</th>
            <th><button onClick={decrease1}>Value -1</button></th>
          </tr>
          <tr>
            <th><button onClick={increase2}>Value +2</button></th>
            <th>{value2}</th>
            <th><button onClick={decrease2}>Value -2</button></th>
          </tr>
        </table>
    </div>
  );
}

export default App;

Output

useReducer Hook

The useReducer hook is similar to the useState hook. It allows you to manage a state and re-render the react component whenever a change in state occurs. The main reason behind using the useReducer hook is that it provides a more concrete way to handle complex state logic. Logics having multiple sub-values or the next step depending on the previous state are called complex states. 

Syntax of useReducer Hook

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

Parameters

  • state: The value of the current state.
  • dispatch: Function that dispatches actions to the reducer function.
  • reducer: We update the state using the reducer function.
  • initialState: Initial value of the state.
  • init: A function that can be used to return the original state. It is called only once during the rendering process.

We will take an example and will demonstrate how the useReducer hook works.

Example

Following is the example of the same counter application that we made in the useState section, but here we are using the useReducer hook to update the state.

import './App.css';
import React, {useReducer} from 'react';

function reducer(state, action){
  switch(action.type){
    case 'increment':
      return {count: state.count+1};
    case 'decrement':
      return {count: state.count-1};
    default:
      return {count: state.count};
  }
}

function App() {

  const [state, dispatch] = useReducer(reducer, {count: 0});

  function increase(){
    dispatch({type: 'increment'});
  }
  function decrease(){
    dispatch({type: 'decrement'});
  }

  return (
    <div className="App">
        <table>
          <tr>
            <th><button onClick={increase}>Increment</button></th>
            <th>{state.count}</th>
            <th><button onClick={decrease}>Decrement</button></th>
          </tr>
        </table>
    </div>
  );
}

export default App;

Output

useReducer hook in reactjs

Explanation

First, we import the useReducer hook from react. The useReducer hook takes two arguments. The first argument is the reducer function, and the second argument is the initial value of the state. The reducer function (first parameter of the hook) takes two parameters: the current state and the action that updates the current state. The reducer function is in charge of updating the state based on the dispatched actions. The useReducer hook returns two values which are current state and dispatch. Dispatch is the function used to dispatch actions to the reducer.

useContext Hook

Before learning about the useContext Hook, we will first learn why we need useContext Hook. So useContext hook is a better version of context api. Both context api and useContext hook are used to pass props from the parent component to the child component. But in the case of context api, it becomes much more difficult and messy code. So to make this process easy, we use the useContext hook. Basically, the useContext hook provides the most efficient way to share data between different components without sharing props at each level.

Syntax of useContext Hook

const value = useContext(context);

Parameters

  • context: We create the context object with the help of createContext function.

We will take an example and will demonstrate how the useContext hook works.

Example

In the following example, we will pass some data from the parent component to the child component using the useContext hook. We will make one child component named “Comp.js”.

App.js

import './App.css';
import React, {createContext} from 'react';
import Comp from './Comp';

const data1 = createContext();
const data2 = createContext();

function App() {

  return (
    <div className="App">
        <data1.Provider value={"Hello Welcome to ExploreUI"}>
          <data2.Provider value={"You are reading about Hooks in ReactJS"}>
            <Comp></Comp>
          </data2.Provider>
        </data1.Provider>
    </div>
  );
}

export default App;
export {data1, data2};

Comp.js

import React, { useContext } from 'react';
import { data1, data2 } from './App';

const Comp = () => {
    const msg1 = useContext(data1);
    const msg2 = useContext(data2);
    return(
        <div>
            <h1>{msg1}</h1>
            <h3>{msg2}</h3>
        </div>
    );
}

export default Comp;

Output

useContext hook in reactjs

Explanation

App.js: In this file, we import createContext from react. Later we create context. In the above example, we are creating two contexts, data1 and data2. Now we pass the contexts using Provider. This syntax will be the same for both context api and useContext hook. 

Comp.js: We first import the useContext hook from react. Later we import the contexts from the App.js component. Now we use the useContext hook to get data from the contexts.

useEffect Hook

Before learning about the useEffect hook, we will first learn why we need the useEffect hook. To provide side effects to the functional component in react, we have to use the useEffect hook. It takes the place of the functionality offered by lifecycle methods in class components. UseEffect Hook is similar to componentDidUpdate, componentDidMount, and componentWillUnmount. Basically, the useEffect hook tells React that the component needs to do an action after rendering.

Syntax of useEffect Hook

useEffect(() => {
  return () => {  }
}, [dependencies]);

The function passed to useEffect will be executed after every render of the component, including the initial render. The values on which an effect depends are specified using the optional dependency array ([dependencies]). It decides how often the effect should be repeated. If the dependency array is not there, then the effect will occur every time a render is made. 

We will take an example and will demonstrate how the useEffect hook works.

Example

In the following example, we will change the state such that a function inside useEffect Hook will be fired.

App.js

import './App.css';
import React, {useEffect, useState} from 'react';

function App() 
{
  const [optionType, setOption] =  useState('Option-1');

  useEffect(() => {
    console.log('Option is Changed');
  }, [optionType])

  return (
    <div className="App">
        <button onClick={() => setOption('Option-1')}>Option 1</button>
        <button onClick={() => setOption('Option-2')}>Option 2</button>
        <button onClick={() => setOption('Option-3')}>Option 3</button>
        <h1>{optionType}</h1>
    </div>
  );
}

export default App;

Output

useEffect hook in reactjs

Explanation

In the above example, we can see that the console prints a message whenever the “optionType” state is changed. We pass optionType as an optional dependency to the useEffect hook so it can monitor the change in the optionType state.

Conclusion

  • To maintain and update the states of the functional components in ReactJS we use Hooks.
  • To manage the state in the functional components we use useState hook.
  • To manage states with complex logic we use the useReducer hook. The reducer function helps useReducer hook to update the state.
  • To pass props from parent to child props we use the useContext hook. It is the alternative to context api.
  • To perform side effects in the functional components we use the useEffect hook. The function inside the useEffect hook is executed whenever there is a change in the state.
0 Shares:
You May Also Like