useEffect hook in react-js
Welcome readers, in this tutorial, we will understand how to use useEffect() hook in a react-js application.
1. Introduction
React is a flexible javascript library responsible for building reusable UI components. It is an open-source component-based frontend library responsible only for the view part of an application and works in a virtual document object model. But before that let us take a look at the differences between angular and react –
Angular | React |
Complete framework | Library |
Object-oriented programming | Extension to the javascript library and its internal architecture is based on jsx |
Based on the model view controller and real document object model | Based on the virtual document object model |
1.1 useEffect hook in react-js
Hooks in react-js are the functions that are hooked into react-js state and lifecycle features from function components. The useEffect(…)
allows performing an effect each time there is a state change. By default, it runs after the first render and every time the state is updated. In the useEffect(…)
method we provide a callback function in the first param and a dependency array in the second param. The dependency array can contain any value and if any of the values changes the component is re-rendered with that updated value. If the dependency array is empty the effect will be executed only once.
1.2 Setting up dependencies
To play with react let us set up some of the required dependencies.
1.2.1 Setting up Node.js
To set up Node.js on windows you will need to download the installer from this link. Click on the installer (also include the NPM package manager) for your platform and run the installer to start with the Node.js setup wizard. Follow the wizard steps and click on Finish when it is done. If everything goes well you can navigate to the command prompt to verify if the installation was successful as shown in Fig. 1.
1.2.2 Setting up react-js project
Once the Nodejs setup is successful we will use the below command to install the react library and set up the project. Do note that the npx
package is available with the npm 5.2 version and above.
Create project structure
$ npx create-react-app useeffect-app
The above command will take some time to install the react library and create a new project named – useeffect-app
as shown below.
2. Understanding useEffect method hook in react-js
To set up the application, we will need to navigate to a path where our project will reside and I will be using Visual Studio Code as my preferred IDE.
2.1 Setting up the react code
To understand a practical implementation let us go through some hands-on exercises.
2.1.1 Creating components
Create a folder named components
in the src
folder.
2.1.1.1 Creating Wrapper component
Create a folder named Wrapper
in the src/components
folder and add the Wrapper.js
file to it.
Wrapper.js
const Wrapper = (props) => { return props.children; }; export default Wrapper;
2.1.1.2 Create Learning component
Create a folder named Learning
in the src/components
folder and add the UseEffectLearning.js
file to it. The file will be responsible to display the input field and validating that input while entering the characters with the help of useEffect()
hook. The input of the field will be stored using the useState()
hook and the validation will take place every time the input changes; giving instant output on the screen.
UseEffectLearning.js
import React, { useEffect, useState } from "react"; import Wrapper from "../Wrapper/Wrapper"; const UseEffectLearning = () => { const [characters, setCharacters] = useState(""); const [isValid, setIsValid] = useState(false); const inputChangeHandler = (e) => { setCharacters(e.target.value); }; // input is started in a state using <code>useState(...)</code> // the validation takes place every time the input changes in the character filed input useEffect(() => { let state = characters.length >= 5 ? true : false; setIsValid(state); }, [characters]); return ( <Wrapper> <label htmlFor="character"> Enter something (more than 4 characters) </label> <input id="character" type="text" onChange={inputChangeHandler} placeholder="Enter something..." ></input> <p> <span style={isValid ? { color: "black" } : { color: "red" }}> {isValid ? "Valid input" : "Invalid input"} </span> </p> </Wrapper> ); }; export default UseEffectLearning;
2.1.2 Creating implementation file
In the App.js
component we will call the child component.
App.js
import "./App.css"; import UseEffectLearning from "./components/Learning/UseEffectLearning"; import Wrapper from "./components/Wrapper/Wrapper"; function App() { return ( <Wrapper> <h2> Learning <code>useEffect</code> in ReactJs </h2> <h3>Running on state change: validating input field</h3> <UseEffectLearning /> </Wrapper> ); } export default App;
3. Run the setup
To run the application navigate to the project directory and enter the following command as shown below in the terminal.
Run command
$ npm run start
The application will be started on the default port. In case the application does not get started on the default port you can change the port number as per your requirement. I have changed the default port to 2000
.
4. Demo
The application will be started in the default browser as shown below and the home page with an Invalid input
message will be shown.
Enter any random text and if the validation passes a Valid input
message will be shown.
That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!
5. Summary
In this tutorial, we created a react application and understood useEffect()
hook in react-js. You can download the source code from the Downloads section.
6. Download the Project
This was a tutorial to understand useEffect()
hook in a react application.
You can download the full source code of this example here: Understanding useEffect hook in react-js