In this article I am going to discuss about useEffect hook in react but before coming to know about useEffect hook if you have not read the article where i discuss how the useState hook work in react then please first understand how useState hook work so you can understand the useEffect hook more clearly. The useEffect hook in React is a function that allows functional components to perform side effects. Side effects refer to operations such as data fetching, subscriptions, manual DOM manipulations, and other interactions with the outside world. This hook enables you to manage these side effects in a React component. The syntax of useEffect hook is given below

useEffect(() => {
  //This is the useEffect syntax that runs the code on every render
});

useEffect(() => {
  //The empty array is used to only run for first render
}, []);

useEffect(() => {
  //This will render for the first time only and when the passed dependency will be 
    changed. Dependency should be any state or prop.
}, [dependency]);

Above is the simple syntax of useEffect code which we can use according to our requirement. Sometimes we also need to cleanup the code in the useEffect to prevent memory leaks or re-rendering of components. so we can cleanup the code like this

import React, { useState, useEffect } from 'react';

function WebSocketComponent({ socketUrl }) {
  const [message, setMessage] = useState('');

  useEffect(() => {
    // Create a WebSocket connection
    const socket = new WebSocket(socketUrl);


    const handleMessage = (event) => {
      setMessage(event.data);
    };


    socket.addEventListener('message', handleMessage);

    // Cleanup code
    return () => {
      socket.removeEventListener('message', handleMessage);
      socket.close();
    };
  }, [socketUrl]);

  return (
    <div>
      <p>Received Message: {message}</p>
    </div>
  );
}

export default WebSocketComponent;

Now lets do a small implementation to understand how the useEffect hook work in the react component.

import { useState, useEffect } from "react";
import ReactDOM from "react-dom/client";

function Counter() {
  const [number, setNumber] = useState(1);
  const [calculateSquare, setCalculateSquare] = useState(1);

  useEffect(() => {
    setCalculateSquare(() => number * number);
  }, [number]); //dependency

  return (
    <>
      <p>The square of {number} is {calculateSquare}</p>
      <button onClick={() => setNumber((c) => c + 1)}>+</button>

    </>
  );
}

In above code we have declared two useStates one is number and other is calculateSquare. So we are simply calculating the square of number. Initially when the useEffect runs the calculateSquare will be 1 but when we click on the button which set the number useState with adding 1 to the previous number. so now our number is two so its square will be updating to 4 automatically without refreshing the page because we have passed the dependency number. So whenever the number state will change the useEffect will render the component again.

Conclusion

In this react hooks tutorial I have discussed about useEffect hook in detail with examples. If you want to know more about the useEffect hook then you can refer to the official documentation of react. In the next article am going to discuss about the useContext hook which is also very one of the important hook in the react. Hope you found this article helpful and like this article.