React Hooks

Back to home
Logicmojo - Updated Aug 28, 2021



React Hooks

React Conf 2018 saw an important innovation in the world of React, namely 'Hooks' (available from v16.8.0), which allows us to use Stateful Component features in Functional Components.

Hooks are essentially functions that allow us to integrate react state and lifecycle features without having to use Classes, as well as organise the logic within a component into reusable, independent parts.

It allowed you to leverage React's state and other capabilities without having to write a class.

🚀 Basic Hooks:
useState
useEffect
useContext

🚀 Additional Hooks
useReducer
useCallback
useMemo

When to use a Hooks

If you create a function component and later wish to add any state to it, you must first convert it to a class. However, you can now do so by incorporating a Hook into an existing function component.

Rules of Hooks

Let's go through a couple of the important rules we must always follow before we develop our own Hook.

⮞ Never call Hooks from inside a loop, condition or nested function
⮞ Hooks should sit at the top-level of your component
⮞ Only call Hooks from React functional components
⮞ Never call a Hook from a regular function
⮞ Hooks can call other Hooks

Let's see some of hooks one by one

useState

The state variable in a functional component is created using this hook, which is the most popular in react.

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



You can use it by passing any value or function as an initial state, and it will return an array of two entities, the first of which is the initial state, and the second of which is a function (dispatcher) that will update the state.

import { useState } from "react";

function App() {
  const [name, setName] = useState("Ayush");
  const changeName = () => {
    setName("Arya");
  };

  return (
    <div>
      <p>My name is {name}</p>
      <button onClick={changeName}> Click me </button>
    </div>
  );
}

export default App;



You must import the useState hook from React in order to use this hook. App is a functional component that we use.

After that, you must establish your state and assign it the value "Ayush" as an initial value (or initial state). name is the name of the state variable, and setName is the function that updates its value.

useEffect Hook

Inside functional components, the useEffect hook allows us to perform side effects and all aspects of lifecycle methods. In contrast to classes, where all connected code is maintained in various lifecycle procedures, it also allows us to organise all related code together.

We construct a state variable count with a value of zero in the example below. Every time a button in the DOM is clicked, the value of this variable is increased by one. Every time the count variable changes, the useEffect hook will run and log some information to the console.

import { useState, useEffect } from "react";

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

  useEffect(() => {
    console.log(`You have clicked the button ${count} times`)
  });

  return (
    <div>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

export default App;



useReducer

It's a substitute for useState. Accepts a reducer of type (state, action) => newState as an argument and returns the current state along with a dispatch function. (If you've used Redux before, you'll understand how this works.)

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



When you have complicated state logic including several sub-values or when the future state is dependent on the prior one, useReducer is usually preferred over useState.

Reducer is a user-defined function that connects the current state to the dispatch method that will handle it, initialArgs refers to the initial arguments, and init is the function that will lazily initialise the state.


app.js

import React, { useReducer } from "react";

// Defining the initial state and the reducer
const initialState = 0;
const reducer = (state, action) => {
switch (action) {
	case "add":
	return state + 1;
	case "subtract":
	return state - 1;
	case "reset":
	return 0;
	default:
	throw new Error("Unexpected action");
}
};

const App = () => {
	// Initialising useReducer hook
const [count, dispatch] = useReducer(reducer, initialState);
return (
	<div>
	<h2>{count}</h2>
	<button onClick={() => dispatch("add")}>
		add
	</button>
	<button onClick={() => dispatch("subtract")}>
		subtract
	</button>
	<button onClick={() => dispatch("reset")}>
		reset
	</button>
	</div>
);
};

export default App;



In Output in every click the count will increase decrease or reset and start with zero


useCallBack

We utilise useCallback to save the callback version that only changes if one of the dependencies changes.

const memorizedFunction = useCallback(fn, [deps]);



If we have a function in the child component that is utilised in the map, anytime the map data is modified, the child component will re-render and a new reference to that function will be generated, therefore we may use useCallback to prevent this.

Conclusion: So there you have it, your journey into the React realm. We've started with Hooks in React to get you familiar with why you'd use in React and what you can do with it.