Blog>
Snippets

Reusing Reactive Effects Across Components

Demonstrate how to create a reusable reactive effect that can be imported and utilized across multiple Vue components.
import { effect } from 'vue';

// A reusable reactive effect function
export function useReactiveEffect(fn) {
  const stop = effect(fn);

  return () => {
    stop(); // Callable function to stop the effect when needed
  };
}
Defines a reusable reactive effect function using Vue's 'effect' function, which can be imported and used in multiple components. It also returns a stop function to clean up the effect.
// ComponentA.js
import { ref } from 'vue';
import { useReactiveEffect } from './useReactiveEffect';

export default {
  setup() {
    const count = ref(0);

    // Use the reusable reactive effect
    const stopEffect = useReactiveEffect(() => {
      console.log(`The count is ${count.value}`);
    });

    // Example of stopping the effect manually
    // stopEffect();

    return { count };
  }
};
Demonstrates how to use the reusable reactive effect 'useReactiveEffect' in a Vue component setup function to reactively log the value of 'count' whenever it changes.
// ComponentB.js
import { ref } from 'vue';
import { useReactiveEffect } from './useReactiveEffect';

export default {
  setup() {
    const name = ref('Vue');

    // Use the reusable reactive effect with a different reactive state
    useReactiveEffect(() => {
      console.log(`The name is ${name.value}`);
    });

    return { name };
  }
};
Shows the reused 'useReactiveEffect' in another component to demonstrate its reusability across different components. This time it watches and logs changes to the 'name' reactive data.