1- import { createContext , useContext , useEffect , useRef , useState } from 'react' ;
1+ import { createContext , useCallback , useContext , useMemo , useRef } from 'react' ;
22
33// Nonces keep track of the order of compositions.
44// It's a counter that goes up and sequences and compositions get a nonce
@@ -11,25 +11,59 @@ export type TNonceContext = {
1111 getNonce : ( ) => number ;
1212} ;
1313
14+ type NonceHistoryItem = [ number , number ] ;
15+
16+ export type NonceHistory = NonceHistoryItem [ ] ;
17+
18+ export type NonceHistoryContext = {
19+ get : ( ) => NonceHistory ;
20+ } ;
21+
1422export const NonceContext = createContext < TNonceContext > ( {
1523 getNonce : ( ) => 0 ,
1624} ) ;
1725
18- export const useNonce = ( ) : number => {
19- const context = useContext ( NonceContext ) ;
20- const [ nonce , setNonce ] = useState ( ( ) => context . getNonce ( ) ) ;
21- const lastContext = useRef < TNonceContext | null > ( context ) ;
26+ let fastRefreshNonce = 0 ;
2227
23- // Only if context changes, but not initially
24- useEffect ( ( ) => {
25- if ( lastContext . current === context ) {
26- return ;
28+ declare const __webpack_module__ : {
29+ hot : {
30+ addStatusHandler ( callback : ( status : string ) => void ) : void ;
31+ } ;
32+ } ;
33+
34+ try {
35+ if ( typeof __webpack_module__ !== 'undefined' ) {
36+ if ( __webpack_module__ . hot ) {
37+ __webpack_module__ . hot . addStatusHandler ( ( status ) => {
38+ if ( status === 'idle' ) {
39+ fastRefreshNonce ++ ;
40+ }
41+ } ) ;
2742 }
43+ }
44+ } catch {
45+ // __webpack_module__ may throw ReferenceError in some environments
46+ }
2847
29- lastContext . current = context ;
48+ export const useNonce = ( ) : NonceHistoryContext => {
49+ const context = useContext ( NonceContext ) ;
50+ const nonce = context . getNonce ( ) ;
51+ const nonceRef = useRef ( nonce ) ;
52+ nonceRef . current = nonce ;
53+ const history = useRef < NonceHistoryItem [ ] > ( [ [ fastRefreshNonce , nonce ] ] ) ;
54+
55+ const get = useCallback ( ( ) => {
56+ if ( fastRefreshNonce !== history . current [ history . current . length - 1 ] [ 0 ] ) {
57+ history . current = [
58+ ...history . current ,
59+ [ fastRefreshNonce , nonceRef . current ] ,
60+ ] ;
61+ }
3062
31- setNonce ( context . getNonce ) ;
32- } , [ context ] ) ;
63+ return history . current ;
64+ } , [ history ] ) ;
3365
34- return nonce ;
66+ return useMemo ( ( ) => {
67+ return { get} ;
68+ } , [ get ] ) ;
3569} ;
0 commit comments