Skip to content

Commit a8518a1

Browse files
authored
chore: less render on the time (#318)
1 parent 7a299d8 commit a8518a1

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

src/hooks/useMergedState.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,17 +16,20 @@ enum Source {
1616
type ValueRecord<T> = [T, Source, T];
1717

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

2121
useLayoutEffect(() => {
22-
if (!firstMount) {
22+
if (!firstMountRef.current) {
2323
return callback();
2424
}
2525
}, deps);
2626

2727
// We tell react that first mount has passed
2828
useLayoutEffect(() => {
29-
setFirstMount(false);
29+
firstMountRef.current = false;
30+
return () => {
31+
firstMountRef.current = true;
32+
};
3033
}, []);
3134
};
3235

tests/hooks.test.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,19 @@ describe('hooks', () => {
281281

282282
expect(container.textContent).toBe('1');
283283
});
284+
285+
it('render once', () => {
286+
let count = 0;
287+
288+
const Demo = () => {
289+
const [] = useMergedState();
290+
count += 1;
291+
return null;
292+
};
293+
294+
render(<Demo />);
295+
expect(count).toBe(1);
296+
});
284297
});
285298

286299
describe('useLayoutEffect', () => {

0 commit comments

Comments
 (0)