ReactJs Global Helper Functions

Nick Pineda picture Nick Pineda · May 13, 2015 · Viewed 32.1k times · Source

Issue: I have a lot of small helper functions that don't necessarily need to live in a component(or maybe they can but they will make that component bloated with a lot of code).My lazy side just wants to just let those all just be some sort of global functions that the components can call.I really want to make good ReactJs code.

Question: What are the best practices in terms of global helper functions in Reactjs? Should I force them into some sort of component or just shove them into the other components?

Basic Example:

function helperfunction1(a, b) {
    //does some work
    return someValue;
}

function helperfunction2(c, d) {
    //does some work
    return someOtherValue;
}

function helperfunction3(e, f) {
    //does some work
    return anotherValue;
}

function helperfunction4(a, c) {
    //does some work
    return someValueAgain;
}


var SomeComponent =
    React.createClass({

        //Has bunch of methods

        //Uses some helper functions

        render: function () {

        }

    });

var SomeOtherComponent =
    React.createClass({

        //Has bunch of methods

        //Uses some helper functions

        render: function () {

        }

    });

Answer

Michiel picture Michiel · Mar 27, 2018

You can export multiple functions from a file, no React needed per se:

Helpers.js:

export function plus(a, b) {
  return a + b;
}

export function minus(a, b) {
  return a - b;
}

export function multiply(a, b) {
  return a * b;
}

export function divide(a, b) {
  return a / b;
}

You can then import the functions you need:

import { multiply, divide } from './Helpers'