Sunday, May 21, 2023

React.js useState, useEffect and useDispatch Hooks Example - Tutorial

Hello guys, if you want to learn about Hooks in React.js like useState, useSelector, useEffect, and useDispatch then you have come to the right place. In the past, I have shared the best React courseswebsites, and books and in this article, I am going to show you what is React hooks and how they make coding and statement management easier in React.js. If you remember, React.js is created by Facebook and ever since it came out in 2013 and since then, it has become one of the biggest players in the front-end development community. Today, React.js demand for frontend development is more than any other framework or library. There are several reasons for its popularity. React is flexible, easy to learn, programmer-friendly, and most importantly, it's high performing. 

Components are the building blocks of a react application. Further, state, props, and lifecycle methods are important parts of React components. Earlier, the React components were created only using classes because state and lifecycle methods were not possible in functional components. 

This was a problem. Writing class components were more complicated than the simple functional components which were nothing but plain JavaScript functions. So in the year 2018, hooks were introduced in the React version 16.8.0.

React hooks changed everything for the react developers. Now, there was no need to write complex class-based components. Instead, simple functional components can be created and with the help of hooks, both state and lifecycle methods could be used. In this article, we will discuss what are react hooks and how can we use them.

By the way, this is the 6th article in my series of React.js for Beginners, covering hooks and state management in depth. Earlier, I have shared how to do state management in ReactuseDispatch and useSelector exampleWhat is Redux and why use itlifecycle methods on functional components, and useState hooks example, if you haven't read them yet, you can read them to learn both React and Redux hooks in depth..   





What is hook in React.js? What problem they solve

In simple words, React hooks are functions that allow the developers to use state and lifecycle features in function components without using classes. React provides several in-built hooks that could be used simply by importing them into the file. Moreover, React also allows the developers to create their own hooks. 

Though React hooks are easy to use there are some rules that you should follow. 

1. Do not use hooks in loops and nested functions. Also, avoid using hooks in conditions. 

2. Hooks should be used in functions. Never use them in classes. 

As mentioned earlier, React provides several in-built hooks. Following is the list of commonly used in-built react hooks.

1. useState

2. useEffect

3. useDispatch 

4. useSelector 

5. useHistory

6. useRef

7. useContext

8. useMemo

9. useLocation

As a professional React.js developer you should know about these 9 frequently used hooks in any react application. If you are not familiar with them and want to learn in depth, I also recommend you to checkout these React.js courses with hooks to start with. 



State Management with hooks

Hooks made it is possible to use states in functional components. The useState hook is used to create the state in functional components. Observe the following code.

import React, { useState } from 'react';
 
function Demo() {
 
  const [counter, setCounter] = useState(0);
 
  return (
 
    <div>
 
      <p>value: {counter}</p>
 
      <button onClick={() => setCounter(counter + 1)}>
 
        Click to add one
 
      </button>
 
    </div>
 
 )
 
}


In the above code, first, the useState hook is imported from React. Observe the following line.


const [counter, setCounter] = useState(0);


The name of the state is "counter" while the "setCounter" is the function that can be used to change the state. Moreover, 0 is passed to the useState hook, meaning, the initial value of the state is 0. Then in the return statement, "setCounter" is used to increment the counter value on every click. 


What are React hooks? Example Tutorial



Lifecycle methods with Hooks

Basically, hooks do not provide any explicit alternative to lifecycle methods. Instead, it provides the useEffect hook which can be used in certain ways to achieve the features equivalent to some lifecycle methods. 

Observe the following code.

import React, { useEffect } from 'react';
 
function Demo() {
 
  useEffect(() => {
 
     //write statements here
 
  });
 
  return (
 
    <div>
 
    </div>
 
  );
 
}

In the above code, the useEffect hook is imported from react and then used in the function. Basically, useEffect is a function and a callback function is it's the mandatory first parameter. 

Let's discuss how we can implement different lifecycle methods using the useEffect hook. 

1. componentDidMount

If the useEffect hook is used with only a single parameter (i.e. callback function), then it is executed after render. But according to componentDidMount logic, it should execute only after the first rendering. So to achieve the logic, we have to pass an empty array as the second parameter.

useEffect(() => {
 
    //write statements here
 
  }, []);

The above useEffect function will execute only after the first rendering. Thus behaving like componentDidMount.


2. componentDidUpdate

According to the componentDidUpdate logic, it should execute immediately after the component is re-rendered. In simple words, if a particular state is changed and the component is re-rendered. To achieve this logic, we can add that particular value to the dependency array, i.e. the array passed as the second parameter. 

useEffect(() => {
 
    //write statements here
 
  }, [value1]);

So, the useEffect will execute every time "value1" is updated. 


3. componentWillUnmount

According to the componentWillUnmount logic, the code should be executed when the component unmounts or is destroyed. If a function is returned from the useEffect hook, the code inside it is executed when the component unmounts. 

useEffect(() => {
 
   return () => {
 
      console.log('Cleaning...') 
 
   }
 
  }, [value1]);


This is how we can use componentWillUnmount with useEffect. 






That's all about Hooks in React.js library. Hooks have become a very important part of React. They have almost eliminated the usage of classes in React components. In this article, we discussed what React hooks are and what are the commonly used hooks. We discussed how the useState hook enables us to use state in functional components. 

Then we discussed how the useEffect hook can be used to achieve different lifecycle logics in functional components. Apart from these, there are several other hooks. The most important ones are react-redux hooks - useDispatch and useSelector.


 Other React and Web development Articles and resources you may like


Thanks for reading this article so far.  If you like this React and Redux hooks tutorial and examples of useEfect hooks, then please share them with your friends and colleagues. If you have any questions or feedback, then please drop a comment.

P. S. - If you are a beginner and want to learn React.js from scratch and looking for free React courses to learn concepts like components, virtual DOM, etc then I also recommend you to join these free online REact.js courses for beginners. It contains free courses from Udemy, Coursera, edX to learn to React online for FREE.       


No comments :

Post a Comment