Skip to content

Commit

Permalink
Merge pull request #660 from optimistiks/fix/usesignal-ssr
Browse files Browse the repository at this point in the history
  • Loading branch information
heyqbnk authored Feb 14, 2025
2 parents d7014ef + b364831 commit 626f803
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .changeset/hot-tables-complain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@telegram-apps/sdk-react": minor
---

Prevent useSignal from erroring out during SSR by passing an optional getServerSnapshot function or the signal itself to useSyncExternalStore
19 changes: 14 additions & 5 deletions packages/sdk-react/src/useSignal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,19 @@ import { useSyncExternalStore } from 'react';
/**
* Returns the underlying signal value updating it each time the signal value changes.
* @param signal - a signal.
* @param getServerSnapshot - an optional function returning the signal value snapshot. It is used only during SSR
* to provide an initial value of the signal. When not set, defaults to the signal itself.
*/
export function useSignal<T>(signal: {
(): T;
sub(fn: VoidFunction): VoidFunction;
}): T {
return useSyncExternalStore((onStoreChange) => signal.sub(onStoreChange), signal);
export function useSignal<T>(
signal: {
(): T;
sub(fn: VoidFunction): VoidFunction;
},
getServerSnapshot?: () => T
): T {
return useSyncExternalStore(
(onStoreChange) => signal.sub(onStoreChange),
signal,
getServerSnapshot || signal
);
}

0 comments on commit 626f803

Please sign in to comment.