Skip to content

Commit

Permalink
Fix: Prevent infinite re-render loop by lazy-loading StoryClient in S…
Browse files Browse the repository at this point in the history
…toryProvider

This change fixes an issue where the StoryClient was being re-created on every render, causing an infinite re-render loop. 
By lazily initializing the StoryClient only once, the component will now only create the client when it's first needed, avoiding unnecessary renders.

Additionally, a loading state is added to improve user experience while the client is being initialized.
This ensures that the component doesn't break or display unexpected behavior during the initialization process.
  • Loading branch information
Himess authored Dec 28, 2024
1 parent e2d628b commit 8818dea
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions packages/react-sdk/src/StoryProtocolContext.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createContext, useContext, ReactNode, useState } from "react";
import { createContext, useContext, ReactNode, useState, useEffect } from "react";
import { StoryClient, StoryConfig } from "@story-protocol/core-sdk";

type Props = {
Expand All @@ -9,16 +9,23 @@ type Props = {
const StoryContext = createContext<StoryClient>({} as StoryClient);

const StoryProvider = ({ config, children }: Props) => {
const [client, setClient] = useState<StoryClient>();
const [client, setClient] = useState<StoryClient | undefined>(undefined);

if (!client) {
useEffect(() => {
setClient(StoryClient.newClient(config));
}, [config]);

if (!client) {
return <div>Loading...</div>; // Loading state while the client is being created
}

return (
<StoryContext.Provider value={client!}>{children}</StoryContext.Provider>
<StoryContext.Provider value={client}>{children}</StoryContext.Provider>
);
};

const useStoryContext = (): StoryClient => {
return useContext(StoryContext);
};

export { useStoryContext, StoryProvider };

0 comments on commit 8818dea

Please sign in to comment.