Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add enabled parameter to useResizeObserver hook #170

Closed
leroykorterink opened this issue May 23, 2023 · 0 comments
Closed

Add enabled parameter to useResizeObserver hook #170

leroykorterink opened this issue May 23, 2023 · 0 comments
Assignees
Labels
question Further information is requested

Comments

@leroykorterink
Copy link
Collaborator

leroykorterink commented May 23, 2023

I don't think this param will be used very often but want to know if we think we need it. I don't know if I like a 4th parameter for the hook function signature. I think it's fine to just do an early return in the callback.

function useResizeObserver(
  target: Unreffable<Element>,
  callback: ResizeObserverCallback,
  options?: ResizeObserverOptions,
  enabled = true,
): void

Implementation will be similar to this:

export function useResizeObserver(
  target: Unreffable<Element>,
  callback: ResizeObserverCallback,
  options?: ResizeObserverOptions,
  enabled = true,
): void {
  const memoizedOptions = useMemo(
    () => options,
    [JSON.stringify(options)],
  );

  const callbackRef = useRefValue(callback);
  const resizeObserver = useClientSideValue(
    () =>
      new ResizeObserver((entries, observer) => {
        callbackRef.current?.(entries, observer);
      }),
  );

  useEffect(() => {
    const element = unref(target);

    if (element === null) {
      return;
    }

    if (enabled) {
      resizeObserver?.observe(element, memoizedOptions);
    } else {
      resizeObserver?.unobserve(element);
    }

    return () => {
      resizeObserver?.unobserve(element);
    };
  }, [enabled, memoizedOptions, resizeObserver, target]);
}

Originally posted by @leroykorterink in #158 (comment)

Solution with enabled parameter

const [enabled, setEnabled] = setState(true);

useResizeObserver(
  target,
  () => {
    // Do something on resize
  },
  {},
  enabled
);

Solution using early return

const [enabled, setEnabled] = setState(true);

useResizeObserver(target, () => {
  if (!enabled) {
    return;
  }

  // Do something on resize
});
@leroykorterink leroykorterink added the question Further information is requested label May 23, 2023
@leroykorterink leroykorterink self-assigned this May 23, 2023
leroykorterink added a commit that referenced this issue Dec 4, 2023
…ack-in-resize-observer

Allow undefined callback in useResizeObserver #170
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

1 participant