Back to Mantine

Use Shallow Effect

apps/mantine.dev/src/pages/hooks/use-shallow-effect.mdx

9.6.01.2 KB
Original Source

import { Layout } from '@/layout'; import { MDX_DATA } from '@/mdx';

export default Layout(MDX_DATA.useShallowEffect);

Usage

The use-shallow-effect hook works exactly like useEffect, but performs shallow dependency comparison instead of referential comparison:

tsx
import { useEffect } from 'react';
import { useShallowEffect } from '@mantine/hooks';

// Will be called on each render
useEffect(() => {}, [{ a: 1 }]);

// Will be called only once
useShallowEffect(() => {}, [{ a: 1 }]);

The hook works with primitive values, arrays, and objects:

tsx
import { useShallowEffect } from '@mantine/hooks';

// Primitive values are handled like in useEffect
useShallowEffect(() => {}, [1, 2, 3]);

// Arrays with primitive values will not trigger callback
useShallowEffect(() => {}, [[1], [2], [3]]);

// Objects with primitive values will not trigger callback
useShallowEffect(() => {}, [{ a: 1 }, { b: 2 }]);

// Arrays with objects will trigger the callback since values are not shallow equal
useShallowEffect(() => {}, [[{ a: 1 }], [{ b: 2 }]]);

Definition

tsx
function useShallowEffect(
  cb: () => void,
  dependencies?: React.DependencyList
): void;