react-use-svelte-store icon indicating copy to clipboard operation
react-use-svelte-store copied to clipboard

Swap `useState` and `useEffect` for useSyncExternalStore

Open Crisfole opened this issue 1 year ago • 4 comments

React 18 introduces useSyncExternalStore as a solution for this exact problem.

We should create new major version of react-use-svelte-store in favor of a version that uses the correct tool for the job.

This will involve some (very annoying) build configuration changes to support security enhancements for both major versions.

Crisfole avatar Aug 10 '24 14:08 Crisfole

please do :)

sonyarianto avatar Oct 31 '24 13:10 sonyarianto

@Crisfole

Is this correct?

import { useSyncExternalStore } from 'react';
import { get, writable, readable, derived, Writable, Readable } from 'svelte/store';

export type Setter<T> = (v: T) => void;
export type UpdateFn<T> = (v: T) => T;
export type Updater<T> = (u: UpdateFn<T>) => void;

export function useReadable<T>(store: Readable<T>): T {
  const subscribe = (listener: () => void) => {
    const unsubscribe = store.subscribe(listener);
    return unsubscribe;
  };

  const getSnapshot = () => get(store);

  return useSyncExternalStore(subscribe, getSnapshot);
}

export function useWritable<T>(store: Writable<T>): [T, Setter<T>, Updater<T>] {
  const value = useReadable(store);
  
  return [value, store.set, store.update];
}

// Re-export Svelte's implementations of the stores.
export { get, writable, readable, derived, Writable, Readable };

sonyarianto avatar Oct 31 '24 14:10 sonyarianto

I have genuinely no idea! :D If you test it, and it works, then yes!

With svelte 5 preferring runes to stores this library is becoming less and less needed.

Crisfole avatar Oct 31 '24 15:10 Crisfole

@Crisfole Yes I tested on my website and it works. I am using Svelte 5 (they still not delete store yet) and using React 18.

image

sonyarianto avatar Nov 04 '24 02:11 sonyarianto