@@ -18,6 +18,7 @@ import {
18
18
useContext ,
19
19
createContext ,
20
20
useRef ,
21
+ useCallback ,
21
22
} from "react" ;
22
23
import type { FunctionComponent } from "react" ;
23
24
import { renderToStaticMarkup } from "react-dom/server" ;
@@ -848,4 +849,59 @@ export function updateSignalsTests(usingTransform = false) {
848
849
expect ( cleanup ) . to . have . been . calledWith ( "foo" , isReact16 ? child : null ) ;
849
850
} ) ;
850
851
} ) ;
852
+
853
+ describe ( "useComputed" , ( ) => {
854
+ it ( "should recompute and update dependency list when the compute function changes" , async ( ) => {
855
+ const s1 = signal ( 1 ) ;
856
+ const s2 = signal ( "a" ) ;
857
+
858
+ function App ( { x } : { x : Signal } ) {
859
+ const fn = useCallback ( ( ) => {
860
+ return x . value ;
861
+ } , [ x ] ) ;
862
+
863
+ const c = useComputed ( fn ) ;
864
+ return < span > { c . value } </ span > ;
865
+ }
866
+
867
+ await render ( < App x = { s1 } /> ) ;
868
+ expect ( scratch . textContent ) . to . equal ( "1" ) ;
869
+
870
+ await render ( < App x = { s2 } /> ) ;
871
+ expect ( scratch . textContent ) . to . equal ( "a" ) ;
872
+
873
+ await act ( ( ) => {
874
+ s1 . value = 2 ;
875
+ } ) ;
876
+ expect ( scratch . textContent ) . to . equal ( "a" ) ;
877
+
878
+ await act ( ( ) => {
879
+ s2 . value = "b" ;
880
+ } ) ;
881
+ expect ( scratch . textContent ) . to . equal ( "b" ) ;
882
+ } ) ;
883
+
884
+ it ( "should not recompute when the compute function doesn't change and dependency values don't change" , async ( ) => {
885
+ const s1 = signal ( 1 ) ;
886
+ const spy = sinon . spy ( ) ;
887
+
888
+ function App ( { x } : { x : Signal } ) {
889
+ const fn = useCallback ( ( ) => {
890
+ spy ( ) ;
891
+ return x . value ;
892
+ } , [ x ] ) ;
893
+
894
+ const c = useComputed ( fn ) ;
895
+ return < span > { c . value } </ span > ;
896
+ }
897
+
898
+ await render ( < App x = { s1 } /> ) ;
899
+ expect ( scratch . textContent ) . to . equal ( "1" ) ;
900
+ expect ( spy ) . to . have . been . calledOnce ;
901
+
902
+ await render ( < App x = { s1 } /> ) ;
903
+ expect ( scratch . textContent ) . to . equal ( "1" ) ;
904
+ expect ( spy ) . to . have . been . calledOnce ;
905
+ } ) ;
906
+ } ) ;
851
907
}
0 commit comments