ReactJS Hooks: How to Use useEffect in ReactJS?

To give an initial state sometime we need an auto refresh state such as to display a realtime data in our page. And to support this activity we need to use a kind of Hooks which is called useEffect.

  • When you call useEffect with only the callback function, useEffect runs on every render. useEffect(() => {});
  • When you call useEffect with empty array of dependencies, the useEffect run only once at the first render. useEffect (() => {}, []);
  • When you call useEffect with an array of dependencies, useEffect runs everytime one of the dependencies changes. useEffect(() => {}, [array, of, dependencies]);

Below as a sample in using useEffect:
import React, { useState, useEffect } from 'react';

function Example() {
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 (
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me

For more advance in useEffect implementation can be read from below project URL where I use this method to display initial data automatically.


Popular posts from this blog

How to Inspect Problems in Your ReactJS Codes