React Hooks

The official launch of React 16.8 took place in early February, which came with a new API that enables state and other capabilities to be used in React without developing a class. Hooks is the name of this additional API, which is growing in popularity throughout the React ecosystem, spanning open-source projects to being employed in live apps. Hooks are the functions that allow function components to "hook into" state and lifecycle elements of the React framework. Since Hooks are backward-compatible, they don't include any fundamental modifications. It also doesn't take the place of your understanding of React ideas. Let us dive deeper into the world of React Hooks.

What are React Hooks?

React Hooks are built-in features that let developers utilize state & lifecycle methods inside of functional components. Since they cooperate with existing code, they are simple to integrate into a codebase. Hooks were advertised to the general public as allowing developers to leverage state in functional components, but they are actually much more potent than that. They make it possible for React developers to gain these advantages:

  • Improved defaults, 
  • Better composition of code, and
  • Improved reuse of code;
  • Flexibility in navigating upward and downward the components tree;
  • The ability to share non-visual logic through the usage of custom hooks.

React Hooks give developers the ability to leverage functional components for nearly all of their needs, from UI rendering to handling data and logic.

Why the need for Hooks?

We will now look into some reasons why you should consider using React Hooks:

  • Use of ‘this’ keyword: Classes are a barrier to learning React well since you must comprehend how the "this" keyword works in JavaScript, which is different from other languages. This issue is resolved with React Hooks, which lets developers leverage the best React capabilities without the use of classes.
  • Reusable stateful logics: Logic and UI are simpler to separate when using hooks. No need for render props or HOC. With decreased boilerplate and more logical UI and logic compositions, hooks do it beautifully. Without altering the design or structure of your components, you can reutilize logic between them by using hooks. When sharing components via tools and platforms like Bit (Github), this "elegant separation" is especially important because each (independently shared) component is much simpler to comprehend, maintain, and reuse across other projects.
  • Simplifying complex scenarios: It is harder to grasp with time as components grow bigger and perform more functions. Instead of needing to impose a split based on lifecycle methods, hooks allow you to divide a single component into numerous smaller functions based on how the various components of this detached component are linked (such as setting up a subscription or requesting data).

What are the Rules Of Hooks?

Hooks are comparable to JavaScript functions, however, when utilizing them, you must adhere to these two guidelines. All stateful logic in a component is guaranteed to be transparent in its source code by the hooks rule. They are as follows:

  • Only make top-level calls to Hooks: In loops, nested functions, or conditions, do not call Hooks. Hooks ought to be employed at the highest level of React functions at all times. This rule makes sure that each time a component renders, Hooks are called in the same order.
  • Just use Hooks when calling React functions: Hooks are inaccessible from standard JavaScript functions. Instead, React function components can call Hooks. Additionally, custom Hooks may call hooks.

To gain in-depth knowledge with practical experience in React Js, Then explore HKR's React JS Training

React JS Training

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning

How to install react hooks

The following commands must be entered in order to use React Hooks:

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

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

The aforementioned command will install the most recent alpha versions of React and React-DOM that enable React Hooks. Verify the package. The React and React-DOM dependencies are listed in the JSON file as follows.

"react": "^16.8.0-alpha.1",  

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

ReactJs Hooks State

Without having to change a functional component into a class component, React developers can update, handle, and modify the state inside of it using the useState() hook. Let us use an example:

function App() {
const [age, setAge] = useState(19);
const handleClick = () => setAge(age + 1)
   return
       <div>
       Hi, My age is {age} years
       <div>
       <button onClick={handleClick}>Increase my age! </button>
       </div>
      </div>
}

As you may have seen, our component lacks the complexity of a class component and appears to be rather straightforward, concise, and functional.

The two variables in the array can be given names by using JavaScript's array destructuring in the useState() hook, which takes a starting state as an argument before returning. The first variable represents the actual state, and the second is a function that can be used to provide a new state in order to update the first variable.

Output: Hi, My age is 19 years “Increase My age”

The state of the age will modify when you click the "Increase my Age" button, and the component will function similarly to a class component with state as a result.

ReactJs Hooks Effect

We can carry out side effects (an action) in the function components thanks to the Effect Hook. It does not use the lifecycle methods for components found in the class components. In other words, componentDidMount(), componentDidUpdate(), and componentWillUnmount() lifecycle functions are comparable to Effects Hooks.

Most online applications need to execute certain functions that side effects have in common, such as:

  • DOM updating,
  • Obtaining and using information from a server API,
  • A subscription setup, etc.

Let's examine the Hook Effect using the following illustration.

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;

There are 2 kinds of side effects in the React component:

  • Effects Without Cleanup: It is utilized in useEffect, which permits the browser to update the screen without being hindered. The app is more responsive as a result. Effects that don't need to be cleaned up include manual DOM changes, network queries, logging, etc.
  • Effects With Cleanup: Cleaning up some impacts after DOM updating is necessary. For instance, it's crucial to clean up memory before setting up a subscription to an external data source to avoid creating a memory leak. The memory cleanup in React is done when the component unmounts. However, as we are all aware, effects are executed many times for each rendering method. As a result, React also eliminates effects from the preceding render before applying them again.

ReactJs Custom Hooks

A unique JavaScript function is called a hook. Custom Hooks have names that begin with "use," which can be used to summon other Hooks. A regular function is the same as a custom Hook, and the term "use" at the beginning indicates that the function abides by the rules of hooks. You can convert component logic into functions that can be reused by creating unique Hooks.

Let's use the example below to further understand how custom Hooks function.

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;

UseDocumentTitle is a custom Hook in the excerpt above that accepts a string of text as an argument that represents the title of the document. We call useEffect Hook inside of this Hook and set the title if the title has changed. Only if its local state differs from what we are putting in, will the second argument run that check and change the title.

ReactJS useReducer Hook

The usage When you have sophisticated state-building logic, when the future state value depends on the previous value, or when the components need to be optimized, Reducer Hook is a better alternative to useState hook and is typically recommended over it.

The useReducer hook requires three arguments, including the reducer, the method to lazily load the initial state, and the reducer. The following is the syntax:

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

Let us take an example:

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;

Output:

0

“Add”

“Subtract”

“Reset”

Want to know more about React Js,visit here React Js Tutorial!

Subscribe to our youtube channel to get new updates..!

React JS useRef Hook

UseRef produces a ref object that is modifiable. The object has an attribute referred to as .current. The refContainer.current property retains the value. These values can be obtained through the returning object's current property. The given input initialValue, such as useRef, could be used to initialize the.current property (initialValue). The component's whole lifetime can be preserved by the object by storing a value. The following is the Syntax:

const refContainer = useRef(initialValue);

Let us take an example:

import React, {Fragment, useRef} from 'react';

function App() {
// Creating a ref object using useRef hook
   const focusPoint = useRef(null);
   const onClickHandler = () => {
      focusPoint.current.value =
      "The quick brown fox jumps over the lazy dog";
      focusPoint.current.focus();
  };
    return (
      <Fragment>
       <div>
             <button onClick={onClickHandler}>
              ACTION
             </button>
       </div>
       <label>
      Click on the action button to
      focus and populate the text.
      </label><br/>
     <textarea ref={focusPoint} />
     </Fragment>
  );
  };
  export default App;

Output:
In this example, the textarea is focused using the useRef hook by the onClickHandler, which is activated anytime the ACTION button is clicked. The useRef object, which was initially initialized to null and whose value is changing to the onClick event, is the focusPoint. Check out the output of the aforementioned code.

ReactJS useLayoutEffect Hook

Similar in operation to the useEffect hook, the useLayoutEffect hook fires synchronously only after all DOM loading has been completed. This is helpful for both reading the layout from the DOM and for synchronously re-rendering the DOM. But we should always utilize the useEffect hook to avoid stopping the page from loading.

The componentDidMount & componentDidUpdate methods and the useLayoutEffect hook all operate during the same phase. UseLayoutEffect should only be used if useEffect is failing to get the desired outcome. The syntax for useLayoutEffect is:

useLayoutEffect()

Let us take an example:

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

const App = () => {
const [value, setValue] = useState('GFG');

useLayoutEffect(() => {
     if (value === 'GFG') {
     // Changing the state
    setValue('GeeksForGeeks');
  }
    console.log('UseLayoutEffect is called with the value of ', value);
  }, [value]);

  return <div>{value} is the greatest portal for geeks!</div>;
 };

export default App;

Use the following command to launch the program from the project's root directory:

npm start
The desired Output will then be displayed.

React JS useMemo Hook

The hook called useMemo in React's functional component returns a value that has been memoized. Memorization is a broad term used in computer science when we don't need to recompute a function with a particular parameter the next time because it delivers the cached result. A memoized function keeps track of the outcomes for a specific set of inputs. For instance, if a function exists to add two numbers, and we pass in the parameters 1 and 2 for the first time, the function will add these two numbers and return 3, but if the same inputs are provided again, we will return the cached value, or 3, rather than performing the add function calculation once more. When the state and props of a React component remain constant and the component does not re-render, we use this idea to ensure that the component displays the same output. The useMemo hook enhances our React application's performance.

The Syntax for useMemo is:

const memoizedValue = useMemo(functionThatReturnsValue, arrayDepencies)

Let us take an example:

import React, {useState} from 'react';

function App() {
   const [number, setNumber] = useState(0)
   // Using useMemo
   const squaredNum = useMemo(()=> {
   return squareNum(number);
   }, [number])
const [counter, setCounter] = useState(0);

// Change the state to the input
const onChangeHandler = (e) => {
   setNumber(e.target.value);
  }

// Increases the counter by 1
const counterHander = () => {
   setCounter(counter + 1);
  }
return (
     <div className="App">
     <h1>Welcome to Geeksforgeeks</h1>
     <input type="number" placeholder="Enter a number"
     value={number} onChange={onChangeHandler}>
      </input>
     <div>OUTPUT: {squaredNum}</div>
     <button onClick= {counterHander}>Counter ++</button>
    <div>Counter : {counter}</div>
    </div>
  );
  }

// function to square the value
function squareNum(number){
console.log("Squaring will be done!");
return Math.pow(number, 2);
 }

export default App;

The function that returns the value, squareNum, is supplied inside the useMemo in the example above, and inside the array dependencies, we have used the number because squareNum will only run when the number changes. The squareNum function does not execute again if the counter is increased but the value entered in the input field does not change.

React JS Training

Weekday / Weekend Batches

 Conclusion

We chose classes for React components because, at the time, functional components couldn't be used to construct a state or implement lifecycle methods. By providing a way to write code that is clearer, more comprehensible, adaptable, and expandable than utilizing class components without hooks, react hooks have made implementing these functionalities considerably simpler. React has become a popular front-end framework many businesses use, encouraging more developers to add it to their knowledge base.

Other Articles :

Find our upcoming React JS Training Online Classes

  • Batch starts on 1st Feb 2023, Weekday batch

  • Batch starts on 5th Feb 2023, Weekend batch

  • Batch starts on 9th Feb 2023, Weekday batch

Global Promotional Image
 

Categories

Request for more information

Webinar

Register Live Digital Marketing Webinar

29th January | 07:00 pm

2 Registered

Amani
Amani
Research Analyst
As a content writer at HKR trainings, I deliver content on various technologies. I hold my graduation degree in Information technology. I am passionate about helping people understand technology-related content through my easily digestible content. My writings include Data Science, Machine Learning, Artificial Intelligence, Python, Salesforce, Servicenow and etc.

Never utilize early returns in your React method; instead, use Hooks at the Top level. You can guarantee that Hooks are called in the same order every time a component renders by adhering to this rule. This is what enables React to maintain Hook state appropriately between useState and useEffect calls.

Hooks were a significant advancement in React. React apps are now more powerful, easier to use, and need less coding. While there are several Hooks in existence, you definitely should be aware of the five fundamental React hooks which are: useState, useEffect, useRef, useContext, useReducer

Some of the best react courses are as follows:

  • React - The Complete Guide (incl Hooks, React Router, Redux)
  • Modern React with Redux.
  • Complete React Developer in 2022 (w/ Redux, Hooks, GraphQL)

Below are the 5 most important hooks:

1) useState: to manage and save data inside of specific components
2) useEffect: to carry out operations such as sending HTTP requests or utilizing a browser API
3) useRef: to refer to JSX items.
4) useContext: to retrieve data from the React Context to more quickly communicate data between components [instead of sending props]
5) useReducer: to organize data across various components and store it

While there are other hooks than just these 5, they are not as frequently used.

It is possible to divide the built-in hooks into two sections, which are given below.

Basic Hooks

  • useState()
  • useEffect()
  • useContext(

Additional Hooks

  • useReducer()
  • useMemo()
  • useCallback()
  • useImperativeHandle()
  • useDebugValue()
  • useRef()
  • useLayoutEffect()