Codementor Events

Getting to know how to use useState and useEffect in React Hooks

Published Oct 11, 2021
Getting to know how to use useState and useEffect in React Hooks

[1] useState
The most basic of the two hooks I'll discuss in this article. You can have a state variable in a functional component using useState. If you're still perplexed, it's just a regular variable that can cause a component to re-render when the variable's value changes (to be exact, in most cases). As an example,

import { useState } from "react";

function demo() {
const [isVisible, setIsVisible] = useState(true);

return <>{isVisible && <h1>I'm visible</h1>}</>;
}

export default demo;
In a functional component, use useState. The starting value (argument) can be anything, including numbers, boolean values, and so on. True in this circumstance (boolean). This results in an array containing two elements: the actual variable and a function to update the value of that variable. In this situation, we're immediately destructuring the two values, as is customary. It's now just a regular variable. Use the specialized function that we destructured earlier to set its value

setIsVisible(fa lse);
That's it. The only special thing to note is that state variables allow you to re-render components upon change of data (in most cases).

[2] useEffect
It's used in one of the two scenarios below. One is to have something happen when the function in which it is contained is rendered. Another option is to have anything happen when a certain piece of data it's been assigned to monitor changes.

import { useEffect } from "react";

function demo() {
useEffect(() => {
console.log("Like my post!");
}, []);
}

export default demo;
Take note of the second argument, which is an array of dependencies. Because useEffect is not monitoring any data in this scenario, it will not be run (except for the first time this component is rendered). As a result, we'll only notice "Like my post!" for the first time in console.

Case number two:
import { useEffect } from "react";

function demo() {
const data = [1, 2, 3];

useEffect(() => {
console.log("You are the best!");
}, [data]);
}

export default demo;
useEffect is keeping an eye on a variable called data in this case. As a result, if you alter this data a million times, "You are the best!" will appear in console a million times

Discover and read more posts from Prof Lord
get started