logo
Back to blogs

Understanding React's useSyncExternalStore

Mar 10, 2023 - 10 min read

Understanding React's useSyncExternalStore

React 18 introduced a new hook called useSyncExternalStore to help manage state that is external to React. This hook is particularly useful for integration with external data source or libraries that manage their own state .In this blog we'll explore how to use useSyncExternalStore

What is useSyncExternalStore?

the useSyncExternalStore hook is designed to subscribe to an external store and ensure that your react react component stay in sync with the store's state It takes three arguments:

  • subscribe: A function that subscribes to the external store and return unsubScribe function.
  • getSnapshot: A function that returns the current value of the external store.
  • getServerSnapshot: A function that returns the server-rendered value of the external store.

The useSyncExternalStore hook is designed to subscribe to an external store and ensure that your React component stays in sync with the store's state. It takes three arguments:

MyLocation.tsx
1import { useSyncExternalStore } from "react"; 2type LocationData = 3 | { status: "unavailable"; geo?: never } 4 | { status: "available"; geo: GeolocationPosition }; 5// this variable is our external store! 6let location: LocationData = { status: "unavailable" }; 7 8function subscribeToGeolocation(callback: () => void) { 9 const watchId = navigator.geolocation.watchPosition((position) => { 10 location = { status: "available", geo: position }; 11 callback(); 12 }); 13 return () => { 14 location = { status: "unavailable" }; 15 return navigator.geolocation.clearWatch(watchId); 16 }; 17} 18function getGeolocationSnapshot() { 19 return location; 20} 21function MyLocation() { 22 const location = useSyncExternalStore( 23 subscribeToGeolocation, 24 getGeolocationSnapshot 25 ); 26 return ( 27 <div> 28 {location.status === "unavailable" ? ( 29 "Your location is unavailable" 30 ) : ( 31 <> 32 Your location is {location.geo.coords.latitude.toFixed(2)} 33 {"°, "} 34 {location.geo.coords.longitude.toFixed(2)} 35 {"°"} 36 </> 37 )} 38 </div> 39 ); 40}

Here's the basic API:

MyLocation.tsx
1const snapshot = useSyncExternalStore( 2 subscribe, 3 getSnapshot, 4 getServerSnapshot // optional 5);