Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import {
useImperativeHandle,
useMemo,
useRef,
useState,
} from 'react';

import { AutocompleteMenuProps } from './AutocompleteMenu.types';
Expand All @@ -19,7 +18,7 @@ import { useOverlayScrollbars } from 'overlayscrollbars-react';

import clsx from 'clsx';

import { useForkRef, useIntersectionObserver, useScrollLock } from '../../hooks';
import { useForkRef, useIntersectionObserver, useRefState, useScrollLock } from '../../hooks';
import { IconCloseLineW350, IconMagnify2LineW400 } from '../../icons';
import { useDefaultProps } from '../../theming';
import { Button } from '../Button';
Expand Down Expand Up @@ -107,7 +106,7 @@ export const AutocompleteMenu = (({ ref, ...inProps }: AutocompleteMenuProps<any
const searchInputRef = useRef<FormFieldInputElement | null>(null);
const handleSearchInputRef = useForkRef(searchInputRef, SearchProps?.inputRef);
const menuListRef = useRef<HTMLUListElement | null>(null);
const [sentinelRef, setSentinelRef] = useState<HTMLElement | null>(null);
const [sentinelRef, setSentinelRef] = useRefState<HTMLElement>();

const [initialize, instance] = useOverlayScrollbars({ options: OVERLAY_SCROLLBARS_OPTIONS, defer: true });

Expand Down Expand Up @@ -137,7 +136,7 @@ export const AutocompleteMenu = (({ ref, ...inProps }: AutocompleteMenuProps<any
}, {});
}, [valueArray]);

useIntersectionObserver({ current: sentinelRef }, (entries) => {
useIntersectionObserver(sentinelRef, (entries) => {
if (onLoadMore && entries[0].isIntersecting) {
onLoadMore();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
'use client';

import { Children, RefAttributes, useState } from 'react';
import { Children, RefAttributes } from 'react';

import { FiltersFormGroupProps } from './FiltersFormGroup.types';

import { OverlayScrollbarsComponentRef } from 'overlayscrollbars-react';

import clsx from 'clsx';

import { useBoolean, useScrollPosition } from '../../../hooks';
import { useBoolean, useRefState, useScrollPosition } from '../../../hooks';
import { useDefaultProps } from '../../../theming';
import { Link } from '../../Link';
import { OverlayScrollbars } from '../../OverlayScrollbars';
Expand All @@ -26,9 +26,9 @@ export const FiltersFormGroup = ({ ref: inRef, ...inProps }: FiltersFormGroupPro

// The viewport is published from `onInitialized` rather than read off the ref during render, which
// would have made the observed element depend on a value that cannot trigger a re-render.
const [viewport, setViewport] = useState<HTMLElement | null>(null);
const [viewport, setViewport] = useRefState<HTMLElement>();

const { isScrollableY, isAtTop, isAtBottom } = useScrollPosition({ current: viewport });
const { isScrollableY, isAtTop, isAtBottom } = useScrollPosition(viewport);

const onInitialized = (instance: NonNullable<ReturnType<OverlayScrollbarsComponentRef['osInstance']>>) => {
setViewport(instance.elements().viewport ?? null);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
'use client';

import { RefAttributes, useState } from 'react';
import { RefAttributes } from 'react';

import { SidebarScrollableProps } from './SidebarScrollable.types';

import { OverlayScrollbarsComponentRef } from 'overlayscrollbars-react';

import clsx from 'clsx';

import { useScrollPosition } from '../../../hooks';
import { useRefState, useScrollPosition } from '../../../hooks';
import { useDefaultProps } from '../../../theming';
import { OverlayScrollbars } from '../..//OverlayScrollbars';

Expand All @@ -26,9 +26,9 @@ export const SidebarScrollable = ({

// The viewport is published from `onInitialized` rather than read off the ref during render, which
// would have made the observed element depend on a value that cannot trigger a re-render.
const [viewport, setViewport] = useState<HTMLElement | null>(null);
const [viewport, setViewport] = useRefState<HTMLElement>();

const { isScrollableY, isAtTop, isAtBottom } = useScrollPosition({ current: viewport });
const { isScrollableY, isAtTop, isAtBottom } = useScrollPosition(viewport);

const onInitialized = (instance: NonNullable<ReturnType<OverlayScrollbarsComponentRef['osInstance']>>) => {
setViewport(instance.elements().viewport ?? null);
Expand Down
1 change: 1 addition & 0 deletions packages/react/src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export type { UsePaginationItem, UsePaginationProps, UsePaginationResult } from
export { usePagination } from './usePagination';
export { usePermission } from './usePermission';
export { usePreviousValue } from './usePreviousValue';
export { useRefState } from './useRefState';
export { useResizeObserver } from './useResizeObserver';
export { useScrollDirection } from './useScrollDirection';
export { useScrollLock } from './useScrollLock';
Expand Down
1 change: 1 addition & 0 deletions packages/react/src/hooks/useRefState/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { useRefState } from './useRefState';
27 changes: 27 additions & 0 deletions packages/react/src/hooks/useRefState/useRefState.api.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Meta } from '@storybook/addon-docs/blocks';
import LinkTo from '@storybook/addon-links/react';
import { TableFunction } from '~storybook/components/TableFunction';

<Meta title="Hooks API/useRefState" />

# useRefState API

```js
import { useRefState } from '@esfront/react';
```

<TableFunction name="useRefState" />

<br />

<br />

## Demos

<ul>
<li>
<LinkTo kind="hooks-useRefState" story="demo">
<code>useRefState</code>
</LinkTo>
</li>
</ul>
60 changes: 60 additions & 0 deletions packages/react/src/hooks/useRefState/useRefState.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { useState } from 'react';

import { Meta, StoryObj } from '@storybook/react-vite';

import { useRefState } from './useRefState';

import { useResizeObserver } from '../useResizeObserver';

const meta: Meta = {
tags: ['autodocs'],
title: 'Hooks/useRefState',
parameters: {
references: ['useRefState'],
},
};

export default meta;

type Story = StoryObj;

export const Demo: Story = {
render: function Render() {
const [isMounted, setMounted] = useState(false);
const [width, setWidth] = useState(0);

// A plain `useRef` would not work here: the box is mounted after the first render, and writing
// to a ref does not re-render, so `useResizeObserver` would never pick the node up.
const [box, setBox] = useRefState<HTMLDivElement>();

useResizeObserver(box, (entries) => {
setWidth(entries[0].target.clientWidth);
});

return (
<div className="flex flex-col gap-16" style={{ alignItems: 'flex-start' }}>
<label className="body100 flex gap-8">
<input checked={isMounted} type="checkbox" onChange={() => setMounted((value) => !value)} />
Mount the observed box
</label>
{isMounted && (
<div
ref={setBox}
className="body100"
style={{
resize: 'horizontal',
overflow: 'auto',
width: '200px',
padding: '8px',
border: '1px solid var(--es-mono-a-a150)',
borderRadius: '4px',
}}
>
Drag my bottom right corner
</div>
)}
<div className="body100">Observed width: {width}px</div>
</div>
);
},
};
29 changes: 29 additions & 0 deletions packages/react/src/hooks/useRefState/useRefState.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
'use client';

import { RefObject, useCallback, useRef } from 'react';

import { useForceUpdate } from '../useForceUpdate';

/**
* The hook that keeps a value in a ref and re-renders the component whenever that value is set. Useful for feeding a
* DOM node to the hooks that observe `ref.current`, such as `useResizeObserver` or `useIntersectionObserver`, which a
* plain `useRef` cannot do because writing to it does not trigger a render.
* @param initialValue The value the ref is initialized with.
* @returns The ref and a setter which can be passed directly to the `ref` prop as a callback ref.
*/
export const useRefState = <T>(initialValue: T | null = null): [RefObject<T | null>, (value: T | null) => void] => {
const ref = useRef<T | null>(initialValue);
const forceUpdate = useForceUpdate();

const setRef = useCallback(
(value: T | null) => {
if (ref.current !== value) {
ref.current = value;
forceUpdate();
}
},
[forceUpdate]
);

return [ref, setRef];
};
Loading