Skip to content

Commit

Permalink
chore: less render on the time (#318)
Browse files Browse the repository at this point in the history
  • Loading branch information
zombieJ authored Jun 23, 2022
1 parent 7a299d8 commit a8518a1
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
9 changes: 6 additions & 3 deletions src/hooks/useMergedState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,20 @@ enum Source {
type ValueRecord<T> = [T, Source, T];

const useUpdateEffect: typeof React.useEffect = (callback, deps) => {
const [firstMount, setFirstMount] = React.useState(true);
const firstMountRef = React.useRef(true);

useLayoutEffect(() => {
if (!firstMount) {
if (!firstMountRef.current) {
return callback();
}
}, deps);

// We tell react that first mount has passed
useLayoutEffect(() => {
setFirstMount(false);
firstMountRef.current = false;
return () => {
firstMountRef.current = true;
};
}, []);
};

Expand Down
13 changes: 13 additions & 0 deletions tests/hooks.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,19 @@ describe('hooks', () => {

expect(container.textContent).toBe('1');
});

it('render once', () => {
let count = 0;

const Demo = () => {
const [] = useMergedState();
count += 1;
return null;
};

render(<Demo />);
expect(count).toBe(1);
});
});

describe('useLayoutEffect', () => {
Expand Down

1 comment on commit a8518a1

@vercel
Copy link

@vercel vercel bot commented on a8518a1 Jun 23, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

util – ./

util.vercel.app
util-git-master-react-component.vercel.app
util-react-component.vercel.app

Please sign in to comment.