Helpers in stateless functional components

If you intend to reuse the helper function, put it outside the stateless component function, either in same file or another, and export it:

export const myHelper = (value) => {
    // Insert logic
};

Otherwise, it's up to you to decide - whatever makes sense to keep things organized.


If you put the helper function inside the component function, everytime the component function gets executed, it will create a new instance of the helper function and after the function was executed the instance possibly gets garbage collected. So typically I would put it outside.

Of course there are exceptions, if you use an arrow function, you might need the lexical scope and therefor put it inside the component function, but if it's a pure function, I would say it should go outside.


You could do something like this, if you want to keep your stateless component pure:

const helpers = { helper: text => text.toUpperCase() }

const makeGreeter = helpers => props => <div>helpers.helper(props.greet)</div>;
const greeter = makeGreeter(helpers);
export default greeter;

This way, your component is a closure encapsulating its own helpers and it has predictable behavior.

As a note: If you modify helper, and you could, because objects are mutable, greeter wouldn't be a pure function.

Tags:

Reactjs