birdofpreyru/react-native-static-server

Using React's useContext to manage server

qwertynik opened this issue ยท 8 comments

Given the ambiguity with which the components unmount on the apps, was considering to use the useContext hook to manage a server. So that, the start/stop/restart/crash handling of a server is done from a central space. However, wanted to know about your experience in doing so before beginning to refactor the existing codebase.

Can you confirm if the usage of useContext would enable better server management? Or, are there any other better approaches to handle this?

I think you can create a context, which holds a useRef reference to the server.
Then you can use the reference to interact with the server from any component. This is not a change that should be added to this library.

This is not a change that should be added to this library.

Not sure why you thought this to be a recommendation for change in the package.

The intent is to know about the pros and cons of this approach, and better yet to know if there are other approaches.

You can just keep your server instance in a dedicated TS module, outside any RN component โ€” you don't really need a context to do what you wanna do here.

Sure, will keep this suggestion in mind when building a project using TS.

Any suggestions on how to best handle a server in a React Native app built using JS?

๐Ÿค” egh... the same โ€” keep it in a dedicated JS module?

Ok. Didn't get it the first time, but now I can see what you are referring to. Something like this should largely work fine, shouldn't it?

const serverProvider = {
    server: null,

    buildServer: function () {
        console.log("Building server...");
        this.server = new Server({...});
        //setup event listener here to track events and reinstantiate server if needed post crashes.
    },

    getServer: function () {
        if (!serverProvider.server) {
            serverProvider.buildServer();
        }

        return serverProvider.server;
    }
}

export default serverProvider;

Yeap.