File tree Expand file tree Collapse file tree 2 files changed +44
-2
lines changed Expand file tree Collapse file tree 2 files changed +44
-2
lines changed Original file line number Diff line number Diff line change
1
+ import React , { useEffect , useState } from 'react' ;
2
+ import { render , screen } from '../test-utils' ;
3
+ import usePrevious from './usePrevious' ;
4
+
5
+ function TestComponent ( { value } : { value : number } ) {
6
+ const prev = usePrevious ( value ) ;
7
+
8
+ return (
9
+ < div >
10
+ < div > current: { value } </ div >
11
+ < div > previous: { prev ?? 'undefined' } </ div >
12
+ </ div >
13
+ ) ;
14
+ }
15
+
16
+ describe ( 'usePrevious' , ( ) => {
17
+ it ( 'should return undefined on first render and previous value after update' , ( ) => {
18
+ const { rerender } = render ( < TestComponent value = { 1 } /> ) ;
19
+
20
+ // First render: previous should be undefined
21
+ expect ( screen . getByText ( 'current: 1' ) ) . toBeInTheDocument ( ) ;
22
+ expect ( screen . getByText ( 'previous: undefined' ) ) . toBeInTheDocument ( ) ;
23
+
24
+ // Update value
25
+ rerender ( < TestComponent value = { 2 } /> ) ;
26
+
27
+ // Second render: previous should be 1
28
+ expect ( screen . getByText ( 'current: 2' ) ) . toBeInTheDocument ( ) ;
29
+ expect ( screen . getByText ( 'previous: 1' ) ) . toBeInTheDocument ( ) ;
30
+
31
+ // Update value again
32
+ rerender ( < TestComponent value = { 3 } /> ) ;
33
+
34
+ expect ( screen . getByText ( 'current: 3' ) ) . toBeInTheDocument ( ) ;
35
+ expect ( screen . getByText ( 'previous: 2' ) ) . toBeInTheDocument ( ) ;
36
+ } ) ;
37
+ } ) ;
Original file line number Diff line number Diff line change 1
1
import { useEffect , useRef } from 'react' ;
2
2
3
- export default function usePrevious ( value ) {
4
- const ref = useRef ( ) ;
3
+ /**
4
+ * Used in Menubar to store the previous value of a number.
5
+ * @param value - The current value to track.
6
+ * @returns The previous value before the current render, or undefined if none.
7
+ */
8
+ export default function usePrevious ( value : number ) : number | undefined {
9
+ const ref = useRef < number > ( ) ;
5
10
6
11
useEffect ( ( ) => {
7
12
ref . current = value ;
You can’t perform that action at this time.
0 commit comments