DEV Community

Nadim Chowdhury
Nadim Chowdhury

Posted on

How to create useEffect hook in vanilla JavaScript?

Creating a useEffect hook equivalent in vanilla JavaScript involves understanding how to manage side effects when certain dependencies change. Here's a simplified example of how you could implement a basic version of useEffect in vanilla JavaScript:

function useEffect(effect, dependencies) {
  // Initialize a variable to keep track of the previous dependencies
  let prevDependencies = [];

  // Check if the dependencies have changed since the last call
  const dependenciesChanged = () => {
    const changed = dependencies.some(
      (dependency, index) => dependency !== prevDependencies[index]
    );
    return changed;
  };

  // Run the effect function if there are no dependencies or if dependencies have changed
  if (!dependencies || dependenciesChanged()) {
    // Call the cleanup function from the previous effect (if any)
    if (typeof cleanup === 'function') cleanup();

    // Run the effect function
    const cleanup = effect();

    // Update the previous dependencies
    prevDependencies = dependencies;
  }
}
Enter fullscreen mode Exit fullscreen mode

Here's how you can use this custom useEffect hook:

// Usage example
let count = 0;

function render() {
  console.log(`Rendered with count: ${count}`);
}

function update() {
  count++;
  render();
}

// Define a side effect to run whenever `count` changes
useEffect(() => {
  console.log(`Count changed to: ${count}`);
}, [count]);

// Update the count
update();
Enter fullscreen mode Exit fullscreen mode

In this implementation:

  • The useEffect function takes two arguments: the effect function to run and an array of dependencies.
  • It compares the current dependencies with the previous dependencies to determine if the effect needs to run again.
  • If there are no dependencies or if dependencies have changed, it runs the effect function and updates the previous dependencies.
  • It also provides a basic cleanup mechanism by calling the cleanup function from the previous effect (if any) before running the new effect.

This implementation is a simplified version of useEffect and doesn't cover all the features and optimizations present in React's useEffect hook, such as cleanup handling, timing of effect execution, and batching of updates. However, it demonstrates the basic idea of how you can create a simple side effect management hook in vanilla JavaScript.

Top comments (0)