useeffect objects in javascript

The useEffect hook is used in React to perform side effects in functional components. useEffect allows us to execute a function/component when certain dependencies change in the component. useEffect takes two parameters, a function to execute and an array of dependencies (optional).

To use useEffect, we first import it from react:

index.tsx
import React, { useEffect } from 'react';
42 chars
2 lines

Once we have imported it, we use it in our functional component like so:

index.tsx
import React, { useEffect, useState } from "react";

function MyComponent() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    // code to perform side effect
  }, [count]);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}
337 chars
17 lines

In this example, we have created a simple state variable count using the useState hook. We then use the useEffect hook to execute some code when the count variable changes.

The function that we pass to useEffect is called the "effect function". This function will be executed when the component mounts and every time the dependencies of the hook change. Dependencies are passed as a second parameter in the form of an array. In this example, we pass [count] as a dependency to useEffect so that the effect function is called every time the value of count changes.

Note that we can omit the array of dependencies if we want to execute the effect function only once, when the component mounts:

index.tsx
import React, { useEffect, useState } from "react";

function MyComponent() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    // code to perform side effect
  }, []);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}
332 chars
17 lines

gistlibby LogSnag