0

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?

1 Answer 1

3

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Sounds good to me. Or maybe export the object from class file itself. Like class Foo {}; export let foo = new Foo();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.