A Look At React Hooks: useSyncExternalStore

A Look At React Hooks: useSyncExternalStore

An awesome library Hook to integrate non-React state management in your apps!

Play this article

Welcome to another article of A Look at React Hooks, a beginner-friendly series on React Hooks. In this article, let's learn about the useSyncExternalStore Hook. It is a useful Hook for when you need to integrate non-React state management in your apps.

Before we begin, you should have a basic knowledge of React and how React Hooks work. If not, please read the React Hook series from the beginning.

What is useSyncExternalStore

useSyncExternalStore a custom hook available in React 18, that lets you subscribe to an external store, reads updated values from that store and updates components if needed.

By 'external store', it means:

  • Third-party state management libraries that hold state outside of React

  • Browser APIs that expose a mutable value and events to subscribe to its changes

Some examples of 'external store' includes:

  • Browser history

  • localStorage

  • Third-party libraries

Why use useSyncExternalStore

According to the official docs, this Hook is useful when you want to update React components when some data in external stores changes. Without useSyncExternalStore Hook, you would need to manually subscribe to these external stores using useEffect.

In some cases, this might cause over-returning Hooks and unwanted re-rendering of components. Hence, it is more optimal to use useSyncExternalStore.

Implementation

Here's a simple example of how to use the Hook:

const externalStore = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot?)

The Hook returns a snapshot of the external store's data you are subscribed to.

  • subscribe : Invokes callback function that triggers when component re-renders. It should also handle the cleanup of the subscription.

  • getSnapshot : This fetches and returns a snapshot of the data subscribed. If the returned value is different, then the component re-renders.

  • getServerSnapshot (optional): This function returns the initial snapshot of the data in the store and provides the snapshot during server-side rendering.

Example

Let's see how this Hook works in an example. Let's say you want to listen for changes in localStorage.

First, you would import the Hook in your component.

import {useSyncExternalStore} from 'react'

Then, you would implement the Hook to read data from localStorage like this:

//this is the subscribe function, listens for changes
const subscribe = (listener) => {
    window.addEventListener("storage", listener);
    return () => {
      window.removeEventListener("storage", listener);
    };
}
//this is the getSnapShot function, returns data subscribed
const getSnapShot = () => {
    localStorage.getItem("example");
}
//implement the Hook
const exampleValue = useSyncExternalStore(subscribe, getSnapShot);

Keep in mind this is a minimalistic example but it should give you a gist on how it works. So the subscribe function will listen for changes in localStorage and handle unsubscribing as well. Then getSnapShot gets the value of the data.

Finally, we use the useSyncExternalStore to ensure the component re-renders whenever a change is detected from localStorage, the external data store we are subscribing to.

For more examples, do visit the official website on useSyncExternalStore.

Conclusion

In conclusion, the useSyncExternalStore Hook has been a great and useful addition to React's kit. It would take time to learn some of the caveats of this Hook and fully understand how to implement it, so I hope this article is a good starting point for you.

Thanks for reading! Please share and like the article if it has been a helpful read. Also, do share in the comments your thoughts on this React Hook. Feel free to check out the References section below to read more. Till next time, cheers!

References

Let's Connect!

Did you find this article valuable?

Support Victoria Lo by becoming a sponsor. Any amount is appreciated!

ย