I follow the approach of creating libraries for cases like this in my applications, and so far this works pretty well for me.

In this case, I would create a new module, e.g. {ComponentRoot}/lib/user.js which exports a function getFullName(user) or possibly getFullName(firstName, lastName, country), depending the circumstances.

Now it is just a matter of importing the module where you require the functionality, no global functions needed:

import React from 'react'
import {getFullName} from '../lib/user'

const Title = ({user}) =>
    <div>
        {getFullName(user)}
    </div>

We place our library folder on the same level as the components folder etc., but whatever works best for you should do.

Answer from TimoStaudinger on Stack Overflow
🌐
Pluralsight
pluralsight.com › blog › guides
Importing Utility Functions in React.js | Online Courses, Learning Paths, and Certifications - Pluralsight
In this guide, you will create a toy app that applies these concepts by separating functions into separate files and importing them from your component. The app takes in the input of BTC (a type of cryptocurrency) and the BTC rate to the dollar and displays the dollars you would have based on those inputs. Start off by creating the component called BTCDollarConverter which looks like the following: import React from 'react'; export default class BTCDollarConverter extends React.Component { constructor(props) { super(props); this.state = { btc: 0.00, btcRate: 0.00, dollars: 0.00 } } handleBtcCh
Discussions

Where to put utility functions in a React-Redux application?
So it's not just "first_name + last_name" but it depends on the country (for example, it would be "last_name + first_name" in China), so there's some relatively complex logic, which I would like to wrap in a function usable from any React component. More on stackoverflow.com
🌐 stackoverflow.com
reactjs - Correct way to share functions between components in React - Stack Overflow
If the logic is relatively-related (they only get used together in the same app), then you should share states between components. But if your logic is distantly-related (i.e., math util, text-formatting util), then you should make and import util class functions. ... var MyComponent = React.cre... More on stackoverflow.com
🌐 stackoverflow.com
Global utility functions in react? How to implement
I want to use a "global function" for the lack of a better word in many of my components, like 80% or more. This function is sort of a repository of messages translated to languages, so I would pas... More on stackoverflow.com
🌐 stackoverflow.com
refactoring - ReactJS hook vs utility function - Software Engineering Stack Exchange
Should we use utility functions in react or should everything be components and hooks? I had this scenario: Utility function for formatting money. const formatMoney = (value) => value == null ? ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
July 15, 2024
🌐
DEV Community
dev.to › trisogene › unlocking-the-power-of-utility-functions-and-custom-hooks-in-react-3mlb
Unlocking the Power of Utility Functions and Custom Hooks in React - DEV Community
June 26, 2024 - // App.js import { capitalizeWords } from "./utils/capitalizeWords"; const App = () => { const title = "welcome to my website"; const subTitle = "im the magical programmer"; const description = "i have a magical refactor wand!"; return ( <div> <h1>{capitalizeWords(capitalizedTitle)}</h1> <h3>{capitalizeWords(subTitle)}</h3> <p>{capitalizeWords(description)}</p> </div> ); }; export default TitleComponent; ... // useLogger.js import { useEffect } from "react"; const useLogger = (message) => { useEffect(() => { console.log(message); }, [message]); }; export default useLogger;
🌐
Medium
samithahewawasam-27681.medium.com › empowering-react-development-essential-utility-functions-0766aef65271
Empowering React Development: Essential Utility Functions | by Samithahewawasam | Medium
May 10, 2024 - import React from 'react'; function ParentComponent({ children }) { const numChildren = React.Children.count(children); // Use numChildren return ( <div> {children} <p>Number of children: {numChildren}</p> </div> ); } These React.Children methods provide useful utilities for working with the children prop in React components, enabling you to manipulate, iterate over, or validate children components more effectively
Top answer
1 of 2
3

So, first of all, your assumption that multiple imports means multiple script executions is probably not true. I just tried it in Node JS and it seems like the re-imported modules were not ran again.

However, you can avoid multiple resource requests by caching the result in a service module. Here's a simple example on stackblitz. The service module only contains a function getData which returns either a promise issuing a request (which also caches the received data) or directly resolves to cached data (if they exist).

    // log this everytime the script is being executed
console.log('get-data.js module being executed');

// just an example
const resourceUrl = 'https://raw.githubusercontent.com/bahamas10/css-color-names/master/css-color-names.json';

let cachedData = null;

const getData = () => {
    if (cachedData === null) {
        console.log('get-data: requesting data');
        return fetch(resourceUrl, {})
        .then(response => {
            cachedData = response.json();
            return cachedData;
        });
    } else {
        console.log('get-data: returning cached data');
        return Promise.resolve(cachedData);
    }
};

export { getData };

In the example, getData is getting executed in an interval every 5s. As you can see though from the log statements only the first call results in a request for fresh data; otherwise the cached data are being served.

I'm also importing getData twice (once in "index.js" and once in "header.js") but the console.log statement in "get-data.j" is only getting executed once. So it's very likely not being executed again after the first import.


If you want to get more fancy, there are a couple of other—arguably more complicated—ways to implement a "global" utility function. For example:

  • Redux middleware, Redux async middleware
  • Dependency injection
2 of 2
1

I suggest keeping your messages in the context and create a component to retrieve the messages from the react context. You can also create a object with the "global" function and inject it with a HOC.

The way I do it is I have a component that uses the react context to retrieve a message using the messages object and current locale to display it in the rendered output. I also created a HOC which injects some helper functions for retrieving messages for placeholders ect.

Find elsewhere
🌐
Stack Exchange
softwareengineering.stackexchange.com › questions › 454148 › reactjs-hook-vs-utility-function
refactoring - ReactJS hook vs utility function - Software Engineering Stack Exchange
July 15, 2024 - The idea of a variable/function is to reuse some logic and it was doing it until it became dependent of something that it can't get itself, since functions can't call hooks. ... const useFormatMoney = (value) => { // or a component const user = useUserContext() return value == null ? '' : user.currency + value.toFixed(2) } I wasn't able to do global replace, because now it has a react rules to follow, it should not be called conditionally, while before it could. After refactoring all those 200+ places, it made me rethink: Every utility function one day can become dependent of something that is not able to get itself.
🌐
GitHub
github.com › Remonhasan › react-utils
GitHub - Remonhasan/react-utils: Functional utils for react application. @antDesign 🦜
A collection of JavaScript utility functions for enhancing and simplifying tasks in React applications.
Author   Remonhasan
🌐
JavaScript in Plain English
javascript.plainenglish.io › utility-functions-in-react-with-code-examples-7df9e7822092
"React Utility Functions" by Deepak Chaudhari | JavaScript in Plain English
October 17, 2024 - “Utility functions are reusable blocks of code that perform specific tasks within a React application. They promote code organization”
🌐
Mobiscroll
docs.mobiscroll.com › overview
General purpose utility functions for React | Mobiscroll
Mobiscroll for React is a collection of React Components that take advantage of React's virtual DOM and state management capabilities.
🌐
Reddit
reddit.com › r/react › where should i put functions that are specific to a component?
r/react on Reddit: Where should I put functions that are specific to a component?
November 2, 2023 -

I noticed I have many components that have functions that are relevant only to them, so I avoided placing these functions in my general services/utilities folders. However sometimes a component of mine will have many functions that are specific to it, and so the file of the component becomes quite long (eg I have a file with 500 lines). I was wondering what is the common way amongst developers of structuring these types of functions or even consts that are related only to a specific component, should I extract them to different files inside the component folder or just leave them in the original file?

🌐
bene : studio
benestudio.co › why-should-we-separate-the-utility-functions
Why Should We Separate the Utility Functions?
May 3, 2018 - These, so-called utility functions, could be for field validation, text formatting, or for some mathematical calculation. How should we create stable, well-tested utility functions, ...
🌐
Odessey blogs
blog.odesseylabs.com › how-to-use-class-to-create-utilities
How to use JavaScript class to create utility function in React JS
March 11, 2023 - I was searching ways to better organise code in React application and I found it is good to use classes in creating utility functions. Here is a program example Utility functions class FormattingUtils { static formatCurrency(amount, currency) { return new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(amount); } static formatPercentage(value,
🌐
GitHub
github.com › wesbos › React-For-Beginners-Transcriptions › blob › master › 08 - Using Utility : Helper Functions in React.md
React-For-Beginners-Transcriptions/08 - Using Utility : Helper Functions in React.md at master · wesbos/React-For-Beginners-Transcriptions
So these are just small little utility functions that I like to use throughout the app, and they're not really associated with any one component, so what I like to do is create a file called helpers.js and this is just full of functions that help me.
Author   wesbos
🌐
Zeromolecule
zeromolecule.com › blog › 5-utility-react-hooks-for-every-project
5 utility React Hooks for every project | Zero Molecule
It runs a callback function only if all dependencies are different than null or undefined. ... useEffect(() => { const notNil = dependencies.every( item => item !== null && item !== undefined ); if (notNil) { return fnRef.current(); } // eslint-disable-next-line react-hooks/exhaustive-deps }, dependencies); }
🌐
freeCodeCamp
freecodecamp.org › news › helper-functions-in-react
How to Write Helper Functions in React
November 2, 2023 - To use helper functions in multiple parts of your project, simply import them as needed. For instance, if you have a utility file with helper functions, import those functions into various components or modules where they are required.
🌐
Reddit
reddit.com › r/reactjs › utility function best practice?
r/reactjs on Reddit: Utility Function Best Practice?
February 15, 2023 -

I have what is essentially a CRUD application with a dashboard component.

The user can create / delete new items on that dashboard.

I have a lot of functions in my dashboard component related to the crud operations (e.g. opening dialogue boxes, adding/removing items, selecting an item etc...) and there are about 170 lines of code dedicated to those operations across different functions.

I've Googled some solutions and it looks like I could store these functions in a utility file and import them to the dashboard component, which would make the dashboard component a lot cleaner.

Is this best practice? While there are a lot of lines of code, they are still generally related to the operations I want to be able to do on the dashboard.

🌐
egghead.io
egghead.io › lessons › react-separate-api-utility-functions-from-react-components
Separate API Utility Functions from React Components | egghead.io
November 19, 2019 - Wrap Fetch Requests to Communicate Pending, Error and Success Status to React Suspense · 5m 41s · 6 · Separate API Utility Functions from React Components · 1m 15s · 7 · Track Async Requests with React's useState Hook · 2m 23s · 8 · Enable Suspense Features with Experimental Concurrent Mode using ReactDOM.createRoot ·