question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Singleton React Component

See original GitHub issue

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… 😄)

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Reactions:1
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

3reactions
PetrykowskiMcommented, Oct 23, 2017

Hello @all,

I would like to revive this conversation by adding another point of view. Wir react@16 it is possible to Mount components into certain points of the DOM by using Portals. For this use case I am building different components like modals or notifications that should be rendered into a certain other component that is mount in my App.jsx like this.

App.jsx

[...]
render() {
  return (<SingletonOverlay></SingletonOverlay>)
}
[...]

Notification.jsx

import React from 'react';
import ReactDOM from 'react-dom';
import NotificationComponent from './Notification.js';
import SingletonOverlay from '../general/Overlay.js';

export default class Notification extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      element: null
    };
  }

  componentDidMount() {
    this.setState({ element: ReactDOM.findDOMNode(SingletonOverlay) });
  }

  render() {
    return this.state.element
      ? ReactDOM.createPortal(
        <NotificationComponent>That is a notification</NotificationComponent>,
        this.state.element,
      )
      : null;
  }
}

The other option would be to find the domNode with document.findElementById or similar functions and pass them to ReactDOM.findDOMNode, which makes me feel very unpleasent as I am forced to leave the “React-Cosmos”.

Therefore I would love to be able to search for Instances of a certain Component that I pass to the function, instead of passing the instance itself, for the above mentioned feature. Im also interested in other approaches on how to solve this problem.

@jimfb would this be worth a feature proposal?

3reactions
zpaocommented, Nov 28, 2015

React component instances have internal state that is needed to know where inside a tree that instance is. You can’t have the same instance rendered in multiple places. Therefore the idea of singleton instances doesn’t make sense in the React world.

What is shown in that fiddle is not really what I would call a singleton mostly because of the single instance argument - it’s more like a module with it’s own state. Then when an instance is rendered, it uses the enclosed (but really “global”) state. It’s cheating and storing a reference to the mounted instance in its global state and forcing an update on the mounted instance. Now there’s nothing actually stopping you from rendering more of these, which would result in the first one not being updated. You could easily do something similar and support rendering more than 1.

As for us making a reference to this in our docs, we won’t do that. There are lots of patterns that could be achieved with React but we’re not going to talk about all of them.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to create shared-singleton components across all the ...
To share data between components, you can : Use a lib like Redux, and keep in shared store your mask loader status; Use...
Read more >
React Design Pattern: Singleton Popup Component
React Design Pattern: Singleton Popup Component. 0. Embed Fork Create Sandbox Sign in. Sandbox Info. React Design Pattern: Singleton Popup Component.
Read more >
Making your App really Sexy with a React Singleton Hook
Singleton hooks are lazy. The body is not executed until the hook is called by some component or other hook. Once loaded, the...
Read more >
Singleton Pattern - Patterns.dev
Singletons are classes which can be instantiated once, and can be accessed globally. This single instance can be shared throughout our application, ...
Read more >
react-singleton-hook - npm
Share custom hook state across all components. Latest version: 4.0.1, last published: 2 months ago. Start using react-singleton-hook in your ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found