@@ -815,6 +815,82 @@ export function useLogger(name, ...rest) {
815815 } , [ ] ) ;
816816}
817817
818+ const dispatchStorageEvent = ( key , newValue ) => {
819+ window . dispatchEvent ( new StorageEvent ( "storage" , { key, newValue } ) ) ;
820+ } ;
821+
822+ const setLocalStorageItem = ( key , value ) => {
823+ const stringifiedValue = JSON . stringify ( value ) ;
824+ window . localStorage . setItem ( key , stringifiedValue ) ;
825+ dispatchStorageEvent ( key , stringifiedValue ) ;
826+ } ;
827+
828+ const removeLocalStorageItem = ( key ) => {
829+ window . localStorage . removeItem ( key ) ;
830+ dispatchStorageEvent ( key , null ) ;
831+ } ;
832+
833+ const getLocalStorageItem = ( key ) => {
834+ return window . localStorage . getItem ( key ) ;
835+ } ;
836+
837+ const useLocalStorageSubscribe = ( callback ) => {
838+ window . addEventListener ( "storage" , callback ) ;
839+ return ( ) => window . removeEventListener ( "storage" , callback ) ;
840+ } ;
841+
842+ const getLocalStorageServerSnapshot = ( ) => {
843+ throw Error ( "useLocalStorage is a client-only hook" ) ;
844+ } ;
845+
846+ export function useLocalStorage ( key , initialValue ) {
847+ const getSnapshot = ( ) => getLocalStorageItem ( key ) ;
848+
849+ const store = React . useSyncExternalStore (
850+ useLocalStorageSubscribe ,
851+ getSnapshot ,
852+ getLocalStorageServerSnapshot
853+ ) ;
854+
855+ const setState = React . useCallback (
856+ ( v ) => {
857+ try {
858+ const nextState = typeof v === "function" ? v ( JSON . parse ( store ) ) : v ;
859+
860+ if ( nextState === undefined || nextState === null ) {
861+ removeLocalStorageItem ( key ) ;
862+ } else {
863+ setLocalStorageItem ( key , nextState ) ;
864+ }
865+ } catch ( e ) {
866+ console . warn ( e ) ;
867+ }
868+ } ,
869+ [ key , store ]
870+ ) ;
871+
872+ React . useEffect ( ( ) => {
873+ if (
874+ getLocalStorageItem ( key ) === null &&
875+ typeof initialValue !== "undefined"
876+ ) {
877+ setLocalStorageItem ( key , initialValue ) ;
878+ }
879+ } , [ key , initialValue ] ) ;
880+
881+ return [ store ? JSON . parse ( store ) : initialValue , setState ] ;
882+ }
883+
884+ export function useLockBodyScroll ( ) {
885+ React . useEffect ( ( ) => {
886+ const originalStyle = window . getComputedStyle ( document . body ) . overflow ;
887+ document . body . style . overflow = "hidden" ;
888+ return ( ) => {
889+ document . body . style . overflow = originalStyle ;
890+ } ;
891+ } , [ ] ) ;
892+ }
893+
818894export function useLongPress (
819895 callback ,
820896 { threshold = 400 , onStart, onFinish, onCancel } = { }
0 commit comments