seventeen
seventeen

Reputation: 443

Sharing a JavaScript class across multiple React components

I have a Javascript class that acts as a data controller to talk to an API.

I need to call methods of that class from multiple react components.

Currently I am storing an instance of the class in the redux store, however I understand thats a bad design approach.

How can I share a single instance across multiple components?

Upvotes: 0

Views: 669

Answers (1)

JAAulde
JAAulde

Reputation: 19560

There are a few ways to handle this. Personally, I use a provider file to export an instance that I can import whenever I need it.

Say I need to use the same instance of a class, Foo, all over my app. I'd import Foo into a provider file that makes and exports an instance of it. Then I'd import the instance from that provider where I needed it:

File, Foo.js:

class Foo {};

export default Foo;

File, FooProvider.js

import Foo from './Foo';

export let foo = new Foo();

Component file:

import foo from './FooProvider';
import React, { Component } from 'react';

Class MyComponent extends Component {
    someMethod () {
        //use foo
    }
}

export default MyComponent;

Upvotes: 3

Related Questions