speechmatics / speechmatics-js-sdk

Javascript and Typescript SDK for Speechmatics
MIT License
39 stars 6 forks source link

useSyncExternalStore for audio access in microphone demo #11

Closed penx closed 1 year ago

penx commented 1 year ago

Use useSyncExternalStore rather than useEffect for audio access

As suggested at https://github.com/speechmatics/speechmatics-js-sdk/pull/6#discussion_r1325953737

From the React docs:

Removing unnecessary Effects will make your code easier to follow, faster to run, and less error-prone. Sometimes, your components may need to subscribe to some data outside of the React state. This data could be from a third-party library or a built-in browser API ... Although it’s common to use Effects for this, React has a purpose-built Hook for subscribing to an external store that is preferred instead. https://react.dev/learn/you-might-not-need-an-effect#subscribing-to-an-external-store

Another reason to add useSyncExternalStore is when you want to subscribe to some value exposed by the browser that changes over time https://react.dev/reference/react/useSyncExternalStore#subscribing-to-a-browser-api

Also