Skip to content

Singleton React Component #5558

@Neta-Alon

Description

@Neta-Alon

Hey guys!
So in this application I'm writing there's a component called "help section". It's basically a box that shows some predefined texts about the component the user's messing with.

I want to be able to tell my "help section" component which component to show help for. As of now, I'm using Flux with some actions and a store. This isn't too bad and works quite nicely, however it's quite a large setup, with 2 files defined specifically for this cause. There are also a number of other issues that I've experienced such as "help section" actions dispatching because of other actions (which raises a "Cannot dispatch in the middle of a dispatch" error).

However, if I could define "help section" as a singleton, I could just import helpSection from './HelpSection and be done with it, since I'll get the instance of "help section". All I have to do is expose a method on helpSection that sets the properties I want to change and call it.

I know it breaks React's unidirectional data flow, with a component changing another component, but maybe it's worth it sometimes. The way I think about it, it's sort of a combination of a store, some actions and a component into one object. A lot of components will only get instantiated once at run time so maybe it'll be quite useful in some cases.

I couldn't find any reference to this on the web other than in this JSfiddle, which seems to work nicely (It's a bit unclear IMO). Is this a good way to do it?

I'm quite a novice in JavaScript and React so I might be missing some obvious points, hopefully not.
What do you think about this?
Thanks for reading.

(P.S. Sorry for any ambiguousness, English is not my native language... 😄)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions