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

feat: add useStateRef hook #1113

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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
6 changes: 6 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@ module.exports = {
],
extends: ['@react-hookz/eslint-config/react', '@react-hookz/eslint-config/jest'],
},
{
files: ['**/__tests__/**/*.jsx', '**/__tests__/**/*.tsx'],
rules: {
'jest/expect-expect': 'off',
},
},
{
files: ['**/__docs__/**', '**/__tests__/**'],
rules: {
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,8 @@ Coming from `react-use`? Check out our
— Like `useSafeState` but its state setter is throttled.
- [**`useValidator`**](https://react-hookz.github.io/web/?path=/docs/state-usevalidator--example)
— Performs validation when any of the provided dependencies change.
- [**`useStateRef`**](https://react-hookz.github.io/web/?path=/docs/state-usestateref--example)
— Hook with callback which provide access to DOM node reference.

- #### Navigator

Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
"@storybook/theming": "^6.5.16",
"@swc/core": "^1.3.28",
"@swc/jest": "^0.2.24",
"@testing-library/react": "12.1.4",
"@testing-library/react-hooks": "^8.0.1",
"@types/jest": "^29.4.0",
"@types/js-cookie": "^3.0.2",
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export * from './useSet';
export * from './useToggle';
export * from './useThrottledState';
export * from './useValidator';
export * from './useStateRef';

// Navigator
export * from './useNetworkState';
Expand Down
23 changes: 23 additions & 0 deletions src/useStateRef/__docs__/example.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import * as React from 'react';
import { useStateRef } from '../..';

export const Example: React.FC = () => {
const [stateRef, setStateRef] = useStateRef((node) => ({
height: node?.clientHeight ?? 0,
width: node?.clientWidth ?? 0,
}));

return (
<div
ref={setStateRef}
style={{
minWidth: 100,
minHeight: 100,
resize: 'both',
overflow: 'auto',
background: 'red',
}}>
<pre>{JSON.stringify(stateRef, undefined, 2)}</pre>
</div>
);
};
36 changes: 36 additions & 0 deletions src/useStateRef/__docs__/story.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { Canvas, Meta, Story } from '@storybook/addon-docs';
import { Example } from './example.stories';
import { ImportPath } from '../../__docs__/ImportPath';

<Meta title="state/useStateRef" component={Example} />

# useStateRef

Hook with callback which provide access to DOM node reference.

#### Example

<Canvas>
<Story story={Example} inline />
</Canvas>

## Reference

```ts
export function useStateRef<Node extends HTMLElement | null, StateRef>(
refCallback: (node: Node) => StateRef
): readonly [StateRef | null, (node: Node) => void];
```

#### Importing

<ImportPath />

#### Arguments

- **refCallback** _`(node: HTMLElement) => unknown`_ - Function which call on mount and unmount of component.

#### Return

- _**[0]**_ _`unknown`_ - return value of `refCallback`
- _**[1]**_ _`(node: HTMLElement) => void`_ - handler which update `stateRef`
139 changes: 139 additions & 0 deletions src/useStateRef/__tests__/dom.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import { renderHook } from '@testing-library/react-hooks/dom';
import { fireEvent, render } from '@testing-library/react';
import React, { useReducer, useEffect } from 'react';
import { useStateRef } from '../../index';

describe('useStateRef', () => {
it('should be defined', () => {
expect(useStateRef).toBeDefined();
});

it('should render', () => {
const { result } = renderHook(() => useStateRef(() => null));
expect(result.error).toBeUndefined();
});

it('should resolve `refCallback`', () => {
const Component = () => {
const [stateRef, setStateRef] = useStateRef(
(node: HTMLDivElement | null) => node?.tagName.toLowerCase() ?? 'none'
);

return (
<div ref={setStateRef}>
<p>my parent is {stateRef}</p>
</div>
);
};

const { getByText } = render(<Component />);

getByText('my parent is div');
});

it('should call once', () => {
const spy = jest.fn();
const Component = () => {
const [stateRef, setStateRef] = useStateRef((node: HTMLDivElement | null) => {
spy();

return node?.tagName.toLowerCase() ?? 'none';
});
const force = useReducer((state) => !state, false)[1];

return (
<div>
<div ref={setStateRef}>
<p>my parent is {stateRef}</p>
</div>
<button type="button" onClick={force}>
force
</button>
</div>
);
};

const { getByText } = render(<Component />);

getByText('my parent is div');

fireEvent.click(getByText('force'));
fireEvent.click(getByText('force'));
fireEvent.click(getByText('force'));

expect(spy).toHaveBeenCalledTimes(1);
});

it('should call on unmount', () => {
const spy = jest.fn();

const Child = () => {
const [stateRef, setStateRef] = useStateRef((node: HTMLDivElement | null) => {
spy();

return node?.tagName.toLowerCase() ?? 'none';
});

return (
<div>
<div ref={setStateRef}>
<p>my parent is {stateRef}</p>
</div>
</div>
);
};
const Parent = () => {
const [displayChild, toggle] = useReducer((state) => !state, true);

return (
<>
{displayChild && <Child />}
<button type="button" onClick={toggle}>
toggle component
</button>
</>
);
};

const { getByText } = render(<Parent />);

getByText('my parent is div');
expect(spy).toHaveBeenCalledTimes(1);

fireEvent.click(getByText('toggle component'));

expect(spy).toHaveBeenCalledTimes(2);
});

it('should call before `useEffect`', () => {
const refCallbackSpy = jest.fn();
const effectSpy = jest.fn();

const Component = () => {
const [stateRef, setStateRef] = useStateRef((node: HTMLDivElement | null) => {
refCallbackSpy();

return node?.tagName.toLowerCase() ?? 'none';
});

useEffect(() => {
if (!refCallbackSpy.mock.calls.length) {
effectSpy();
}
});

return (
<div ref={setStateRef}>
<p>my parent is {stateRef}</p>
</div>
);
};

const { getByText } = render(<Component />);

getByText('my parent is div');

expect(refCallbackSpy).toHaveBeenCalledTimes(1);
expect(effectSpy).not.toHaveBeenCalled();
});
});
13 changes: 13 additions & 0 deletions src/useStateRef/__tests__/ssr.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { renderHook } from '@testing-library/react-hooks/server';
import { useStateRef } from '../..';

describe('useStateRef', () => {
it('should be defined', () => {
expect(useStateRef).toBeDefined();
});

it('should render', () => {
const { result } = renderHook(() => useStateRef(() => null));
expect(result.error).toBeUndefined();
});
});
25 changes: 25 additions & 0 deletions src/useStateRef/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { useCallback, useState } from 'react';

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

/**
* Hook with callback which provide access to DOM node reference.
*
* @param refCallback Function which call on mount and unmount of component
* @returns return value of `refCallback` and handler
*/
export const useStateRef = <Node extends HTMLElement | null, StateRef>(
refCallback: (node: Node) => StateRef
): readonly [StateRef | null, (node: Node) => void] => {
const [stateRef, setStateRefImpl] = useState<StateRef | null>(null);
const syncedRefCallback = useSyncedRef(refCallback);

const setStateRef = useCallback(
(...params: Parameters<typeof refCallback>) => {
setStateRefImpl(syncedRefCallback.current(...params));
},
[syncedRefCallback]
);

return [stateRef, setStateRef] as const;
};
Loading