jost21
jost21

Reputation: 1386

Where to store instance of API object in react (next.js) app?

I'm trying to build react (with next.js) based chat client using the LiveChat CustomerSDK API. I currently use a useEffect hook to initialize and then store the object with a useState hook.

const [customerSDK, setCustomerSDK] = useState();

useEffect(() => {
    const sdk = CustomerSDK.init(config);
    setCustomerSDK(sdk)
}, []);

But I am wondering whether useState is the best way for the customerSDK object, since it doesn't need to trigger a re-render. Therefore I also considered using useRef instead or maybe just storing it in the window object. But neither "feels right".

I have to consider that I need to access the customerSDK object to set the listeners (e.g. customerSDK.on('connected', ...) and also for example sending messages (customerSDK.sendEvent(...)

Is there a recommended/preferred way to approach a situation like this?

Upvotes: 0

Views: 179

Answers (1)

adsy
adsy

Reputation: 11532

Theres another option if you know you only have 1 project accessing it, simply put it in a file and export it, then import this everywhere you need it. If it needs no context (i.e. react state) from your components, why have it stored in a component at all?

const sdk = CustomerSDK.init(config);
export default sdk

Then import that where you need it. It will act as a singleton.

Upvotes: 1

Related Questions