How to store all Functions in one file and inherit it in ReactJS

Viewed 943

I have a question. As in Angular JS we can create a global service file and we can inherit each and every component which obviously allows us to use the functions; written in the global services file, in the respective component.

Do we have the same option in React JS?

2 Answers

React doesn't do "inheritance" and using globals is generally considered bad practice/anti-pattern.

I think the two options you have in React for "globally" accessible functions are to export/import them as named exports/imports from the single file in every file that may need them, or provide them in a React context where any component that needs them can access the Context to get them. Unfortunately for consuming components there's not much difference between the two other than when the "access" is made.

Option 1 - Named Exports/Imports

Export the functions as named exports from the single file:

export const function1 = () => { ..... };
export const function2 = (...args) => { ..... };
...

In any consuming component explicitly import the functions you need:

import { function1, functionN } from '../path/to/global/utils";

...

function1();
  • Pros: Extremely simple to do. Imported files available in file scope.
  • Cons: Could be a bit repetitive do to in every file.

Option 2 - React Context

import { useGlobalContext } from "./GlobalContext";

...

const { function1, function2 } = useGlobalContext();

...

function1();

The setup for this is a little more boilerplatey but leads to a clean API. Create the global context and provide the imported functions as the default context value. Create a custom React hook if you like. Create the context provider component.

import { createContext, useContext } from 'react';
import * as functions from '../path/to/global/utils';

export const GlobalContext = createContext(functions);

export const useGlobalContext = () => useContext(GlobalContext);

const GlobalProvider = ({ children }) => (
  <GlobalContext.Provider value={functions}>
    {children}
  </GlobalContext.Provider>
);

export default GlobalProvider;

Wrap the app with the GlobalProvider. Example index.js:

import { StrictMode } from "react";
import ReactDOM from "react-dom";
import GlobalContext from "./GlobalContext";
import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(
  <StrictMode>
    <GlobalContext>
      <App />
    </GlobalContext>
  </StrictMode>,
  rootElement
);

In any consuming component, use the useGlobalContext hook to access the functions. Example App component:

import { useGlobalContext } from "./GlobalContext";

export default function App() {
  const { function1, function2 } = useGlobalContext();
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      <button type="button" onClick={function1}>
        Global Function 1
      </button>
      <button type="button" onClick={() => function2("TEST ARGUMENT")}>
        Global Function 2
      </button>
    </div>
  );
}

Edit how-to-store-all-functions-in-one-file-and-inherit-it-in-reactjs

  • Pros: Still very simple to do. Very React way to do this.
  • Cons: Functions available only in component scope.

Source

Export function as named exports and import as many of them where ever you want. Example code- create a js file and define as many named export function like below

export const func1=()=>{//function 1} 
export const func2=()=>{//function 2}
export const func3=()=>{//function 3}
export const func4=()=>{//function 4}

import as many of them on any component-

import {func1,func3} from './custom'
Related