Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Swap useState and useEffect for useSyncExternalStore #4

Open
Crisfole opened this issue Aug 10, 2024 · 4 comments
Open

Swap useState and useEffect for useSyncExternalStore #4

Crisfole opened this issue Aug 10, 2024 · 4 comments
Labels
enhancement New feature or request good first issue Good for newcomers

Comments

@Crisfole
Copy link
Owner

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 Crisfole added enhancement New feature or request good first issue Good for newcomers labels Aug 10, 2024
@sonyarianto
Copy link

please do :)

@sonyarianto
Copy link

@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 };

@Crisfole
Copy link
Owner Author

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.

@sonyarianto
Copy link

@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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request good first issue Good for newcomers
Projects
None yet
Development

No branches or pull requests

2 participants