1- import { useContext , useEffect , useState } from "react" ;
1+ import { useContext , useEffect , useRef , useState } from "react" ;
22import { SnapshotContext } from "../../providers/snapshot-provider" ;
33
44export default function useSnapShotState < T > (
@@ -7,25 +7,23 @@ export default function useSnapShotState<T>(
77 onRestore ?: ( value : T ) => void
88) {
99 const snapshotContext = useContext ( SnapshotContext ) ;
10-
1110 if ( ! snapshotContext ) {
1211 throw new Error ( "useSnapShotState must be used within a SnapshotProvider" ) ;
1312 }
1413
1514 const { states, setStates } = snapshotContext ;
16-
17- // Initialize state with the value from context or the initial value
1815 const [ state , setState ] = useState < T > (
1916 states [ key ] !== undefined ? states [ key ] : initialValue
2017 ) ;
2118
22- // Update context whenever state changes
19+ const isLocalUpdate = useRef ( false ) ;
20+
2321 const setSnapshotState : React . Dispatch < React . SetStateAction < T > > = ( value ) => {
2422 setState ( ( prev ) => {
2523 const newValue =
2624 typeof value === "function" ? ( value as ( prev : T ) => T ) ( prev ) : value ;
2725
28- // Defer the setStates call to next microtask, outside render phase
26+ isLocalUpdate . current = true ; // mark as local
2927 Promise . resolve ( ) . then ( ( ) => {
3028 setStates ( ( prevStates ) => ( {
3129 ...prevStates ,
@@ -37,26 +35,31 @@ export default function useSnapShotState<T>(
3735 } ) ;
3836 } ;
3937
40- // Set the initial value in context if not already set
38+ // Initialize context with initial value
4139 useEffect ( ( ) => {
42- // Only set if the key does not exist in the context
4340 if ( states [ key ] === undefined && initialValue !== undefined ) {
44- setStates ( ( prevStates ) => ( {
45- ...prevStates ,
41+ setStates ( ( prev ) => ( {
42+ ...prev ,
4643 [ key ] : initialValue ,
4744 } ) ) ;
4845 }
4946 } , [ ] ) ;
5047
51- // Restore state from context when key or states change
48+ // Only restore when external changes occur
5249 useEffect ( ( ) => {
53- console . log ( "Restoring state for key:" , key , states [ key ] ) ;
50+ const contextValue = states [ key ] ;
51+ if ( contextValue === undefined ) return ;
52+
53+ if ( isLocalUpdate . current ) {
54+ // skip this run because we caused it ourselves
55+ isLocalUpdate . current = false ;
56+ return ;
57+ }
5458
55- if ( states [ key ] !== undefined && states [ key ] !== state ) {
56- setState ( states [ key ] ) ;
57- if ( onRestore ) {
58- onRestore ( states [ key ] ) ;
59- }
59+ if ( contextValue !== state ) {
60+ console . log ( "Restoring state for key:" , key , contextValue ) ;
61+ setState ( contextValue ) ;
62+ onRestore ?.( contextValue ) ;
6063 }
6164 } , [ states [ key ] ] ) ;
6265
0 commit comments