AWS, Cloud Computing

6 Mins Read

ReactJS Hooks: Implementation, Rules, and Uses

TABLE OF CONTENT

1. Introduction to ReactJS
2. React-Hooks
3. Rules to use Hooks
4. Types of Hooks in React
5. Basic Hooks
6. Additional Hooks
7. Using Hooks in ReactJS Application
8. Conclusion
9. About CloudThat
10. FAQs

 

Introduction to ReactJS

There are many popular libraries in JavaScript, and one of the most popular is React. ReactJS is an open-source library, and frontend JavaScript library used to build UI components for web applications. React is based on a component-based approach, making application development faster and easier. However, react is only the “View” part of the popular Model View Controller (MVC) framework. This library is built and maintained by Facebook. By using React, we can create a single page or mobile application. React follows a component-based approach where we have to create a component once and it can be used anywhere in the application.

React-Hooks 

Hooks are the functions that “hooks” state and life cycle features with the functional component. Initially, functional components are known as stateless components; mostly class components are only used. But with the introduction of react-Hooks, there is no need to convert functional components into class components for state management. React hooks take care of the state and life cycle management in functional components. Hooks cannot be used in class components

Rules to use Hooks

  1. Always use hooks at the top level. It cannot be used within loops, conditions, or functions.
  2. Always call hooks from React Components.
  3. Hooks can only be called from custom Hooks where the hook name starts with “use” and they must use useState and useEffect hooks inside them.

Types of Hooks in React

There are many Hooks in ReactJS. In this blog, we will look at all basic hooks and a few additional hooks. We will also look at how we can create our own hook i.e., “Custom Hook”.

Basic Hooks

  1. useState
  2. useEffect
  3. useContext

Additional Hooks

  1. useReducer
  2. useCallback
  3. useMemo
  4. useRef

Using Hooks in ReactJS Application

Let’s set up a ReactJS Web Application. It can be done in a code editor (I am using VS code) and open its terminal to create a new project by typing-

This will create a ReactJS project.

a. useState()

The useState() hook allows the functional component to create its own state. This hook re-renders the UI whenever there is a change in state. useState() is defined as –

Here, this function has the state “count” and setState is a method that is used to set the state of the count. It takes the initial state as an argument inside useState() hook.

To demonstrate the usage open the code editor and create a file “useStateHook.js” in the “src” folder and write the below code.

react1 hook

On click of click button, the incrementCounter function will be called and the value of the count state will increase.

b. useEffect()

useEffect() hook is used as a substitution to class components lifecycle methods. Components use useEffect to execute some logic after rendering the component. We can copy the functionality of lifecycle methods such as componentDidMount, componentDidUpdate, etc. useEffect runs before the first render and after every update because every element requires updated data. We can customize the additional re-rendering by passing some additional arrays.

To demonstrate the usage open the code editor and create a file “useStateHook.js” in “src” folder and write the below code.

react2 hook

Its output will be

react3 hook

After 1 sec

react4 hook

However, if you see the console, you will see that “Inside useEffect will be triggered twice.” It is not optimal behavior because if you have multiple effects, it may trigger the effect multiple times. It may cause infinite loops and may freeze your app.

react5 hook

To optimize this, pass an empty array as a second argument to useEffect hook function. It will trigger useEffect only once.

react6 hook

c. useContext()

useContext hook is used to pass down data from parent component to child component without using props. We can directly pass the data from the provider to the component and avoid the use of Consumer hence doesn’t require nesting.

Create 2 components in the src folder, Component1, and Component2. In Component1 write code-

react7 hook

Here we are creating a UserContext which is like a global state and passing the user state to child components.

In Component2, write code-

react8 hook

Here we are using useContext hook to fetch data from the parent component without using props. Our output will be-

react9 hook

d. useReducer()

useReducer() hook has the same function as that of useState() hook. The main difference between them is that in useReducer(), an action is passed to the reducer function which is responsible for changing the state. It is also used when there are multiple states in our component. useReducer() takes two arguments – a reducer function which is responsible for changing the state and initial state.

Create UseReducer.js component in src folder and write code-

react10 hook

Its output will be –

Initially, the state is 0 and text is visible. With a click of a button, the state of both count and showText is changed. The count is increased to 1 and showText changed to false.

react11 hook

e. useMemo()

useMemo() hook is used where there are expensive, resource extensive functions being called needlessly and thus causes performance issues in our application. useMemo() will cause the function to run only when it is needed. The first argument is a function that contains logic and the second one is the state, which on change calls the function.

f. useRef()

useRef() hook allows us to create a reference to the DOM element in the functional component. The useRef() returns a mutable object  which has a property called .current

This value is persisted for full time in the component.                                                                                                        

Conclusion

Hooks are used to maintaining states in our functional components without changing them into class components.

In this blog, we have learned to use functional hooks and their lifecycle methods to hook the functional components into states.

Feel free to ask any queries you may have while working on Hooks. I will be more than happy to help you.

About CloudThat

CloudThat is the official AWS (Amazon Web Services) Advanced Consulting Partner, Microsoft Gold Partner, Google Cloud Partner, and Training Partner helping people develop knowledge of the cloud and help their businesses aim for higher goals using best-in-industry cloud computing practices and expertise. We are on a mission to build a robust cloud computing ecosystem by disseminating knowledge on technological intricacies within the cloud space. Our blogs, webinars, case studies, and white papers enable all the stakeholders in the cloud computing sphere.

CloudThat is a house of All-Encompassing IT Services on the cloud offering Multi-cloud Security & Compliance, Cloud Enablement Services, Cloud-Native Application Development, and System Integration Services. Explore our consulting here.

If you have any queries about ReactJS or any other file transfer options drop them in the comment section and I will get back to you quickly. Stay tuned for my next blog on a step-by-step guide for streamlining data in real-time.

FAQs:

  1. Which versions of ReactJS hooks are available?

Ans: Starting from 16.8.0, ReactJS includes implementations of Hooks.

  1. What can I do with hooks that I cannot do with classes?

Ans: You do not need to convert your functional components into class components for using states and life cycle features. They can be done in functional components using hooks.

WRITTEN BY Satyam Dhote

SHARE

Comments

    Click to Comment

Get The Most Out Of Us

Our support doesn't end here. We have monthly newsletters, study guides, practice questions, and more to assist you in upgrading your cloud career. Subscribe to get them all!