Helper functions should not depend on the context of the component they are called to (at least in my opinion). If you need to use some parameter in your function passing that to function is always a better practice since it helps on re-usability. The key for the state property might be different for all components and this might lead to errors if you forget to use exact key for the state property.

For Example

export function passwordValidation(password) {
  const length = password.length;
  if (length > 7) return 'success';
  else if (length > 4) return 'warning';
  else if (length > 0) return 'error';
}

If I change function like above I can use all the given examples below.

import { passwordValidation } from '/path/to/helper/functions.js';

console.log(passwordValidation(this.state.password));
console.log(passwordValidation(this.state.confirmPassword));
console.log(passwordValidation(this.props.password));
console.log(passwordValidation(someFetchedObject.user.password));
Answer from bennygenel on Stack Overflow
Top answer
1 of 2
2

Best way to implement this would be creating a separate global component which does this functionality.

Suppose in components.js , you have :

export const  doSomethingElse = () => { 
        return 1;
      }

And wherever you want it you can do by ,

In Cat.js :

import {doSomethingElse} from 'component.js';

doSomethingElse();

Even you can make like a view component like :

export const displayTime = (time) => (
<View>
<Text>{time}</Text>
</View>

)

And you can import in Dog.js like :

import {displayTime} from 'component.js';


render(){
return(
<View>
{this.displayTime('12:00PM');}
</View>
)
}

Hope it helps. feel free for doubts

2 of 2
1

In fact :

  1. any prop is possibly a function render(), it's not only the prop render : https://en.reactjs.org/docs/render-props.html

It’s important to remember that just because the pattern is called “render props” you don’t have to use a prop named render to use this pattern. In fact, any prop that is a function that a component uses to know what to render is technically a “render prop”.

  1. I explain you how work in the design pattern render prop

{this.props.render(this.state)} // It will execute the function (mouse) => Cat mouse={mouse}/> and will instance the component Cat/> with props which are the states of the component Mouse/>

  1. For example, if you want to pass the function doSomethingElse() to the child component , you could do :

    class Mouse extends React.Component {  
      doSomethingElse(){ 
        return 1;
      }
    
    
      render() {
        return (
          <div style={{ height: '100%' }} onMouseMove={this.handleMouseMove}>
            {this.props.render(this.state, this.doSomethingElse)}
          </div>
        );
      }
    }
    
    class MouseTracker extends React.Component {
      render() {
        return (
          <div>
            <h1>Move the mouse around!</h1>
            <Mouse render={(mouse, doSomethingElse, ...props) => (
              <Cat mouse={mouse} doSomethingElse={doSomethingElse} {...props} /> // Possibly others props if you want
            )}/>
          </div>
        );
    
Discussions

java - How to reuse any class or function in react js - Stack Overflow
If you want to reuse non-UI functionality between components, we suggest extracting it into a separate JavaScript module. The components may import it and use that function, object, or a class, without extending it. From Reactjs documentation. More on stackoverflow.com
🌐 stackoverflow.com
October 27, 2017
what is the strategy for reusing small helper functions
Normally I wouldn't put each function in a separate file, but rather group functions that handle similar things together within one file as named exports. For example if I have a number of functions that purely handle custom formatting of numbers, currency units etc. I would have a file called formatter.ts that is setup like so: // Large Number formatters: export const doSomeNumberFormat = () => .... export const someOtherNumFormat = () => .... // Currency Formatters: export const setCurrencyString = () => .... // and so on.... Then could also have another file with functions that only handle say, form based logic, like validating fields, formatting error messages etc. call it formUtils.ts and have that setup in the same way More on reddit.com
🌐 r/reactjs
33
42
October 20, 2021
reactjs - How to create a reusable function in React - Stack Overflow
I'm a quite new to React so sorry if this is a simple question. I have a bunch of components, and for each component I would like to specify an initial state for each of {b: this.constructor.displa... More on stackoverflow.com
🌐 stackoverflow.com
August 10, 2016
reactjs - How to reuse the same functionality in useEffect and another action inside component? - Stack Overflow
I want to reuse the function resolveSessionData() inside a component. It is used to set some state on a prop change as well as in a user action. Is this the correct way to reuse the functionality o... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Medium
medium.com › codezillas › how-to-reuse-react-components-851ffcc68a9c
How To Reuse React Components | by Sabesan Sathananthan | Codezillas | Medium
June 24, 2021 - A component with render props receives a function. This function Return a React element and call it instead of implementing its own rendering logic. Render props is a function props used to tell the component what content needs to be rendered. It is also a way to implement component logic reuse.
🌐
Bitstack
blog.bitsrc.io › reusable-components-in-react-a-practical-guide-ec15a81a4d71
Reusable Components in React — A Practical Guide | by Rajat S | Bits and Pieces
March 6, 2025 - Here, I am changing my message function to Message, changing the function into a component. By doing so, I can use it as a self-closing element inside the App component as shown in the above code snippet. If I change the msg prop to children prop, React will still render the exact same thing. I can even put one Message element inside another Messageelement. class App extends Component { render() { return ( <Message> Hello World <Message>Reusable Components</Message> </Message> ); } }
🌐
Stack Overflow
stackoverflow.com › questions › 46967989 › how-to-reuse-any-class-or-function-in-react-js
java - How to reuse any class or function in react js - Stack Overflow
October 27, 2017 - If you want to reuse non-UI functionality between components, we suggest extracting it into a separate JavaScript module. The components may import it and use that function, object, or a class, without extending it. From Reactjs documentation.
🌐
Rafael Quintanilha
rafaelquintanilha.com › how-to-reuse-logic-with-react-hooks
How to Reuse Logic with React Hooks
October 14, 2024 - Instead, just think that for Hooks any state or prop change calls the function again (recall your component is a function) with the updated values (state and props). For peace of mind, the docs give you a rough equivalency of certain lifecycles in the Hooks world. "[...] Hooks have no lifecycles. For experienced React developers, this can take some time to click. We are used to thinking in terms of componentDidMount, componentWillUpdate, etc. But with Hooks things don’t work this way." My article on learning @reactjs Hooks 👇 https://t.co/8o6tUHkuDE— Rafael Quintanilha (@webquintanilha) June 18, 2019
Find elsewhere
🌐
React
legacy.reactjs.org › docs › hooks-custom.html
Building Your Own Hooks – React
Without it, we wouldn’t be able to automatically check for violations of rules of Hooks because we couldn’t tell if a certain function contains calls to Hooks inside of it. Do two components using the same Hook share state? No. Custom Hooks are a mechanism to reuse stateful logic (such as setting up a subscription and remembering the current value), but every time you use a custom Hook, all state and effects inside of it are fully isolated.
🌐
React
react.dev › learn › reusing-logic-with-custom-hooks
Reusing Logic with Custom Hooks – React
It seems like even though they have different visual appearance, you want to reuse the logic between them. Imagine for a moment that, similar to useState and useEffect, there was a built-in useOnlineStatus Hook. Then both of these components could be simplified and you could remove the duplication between them: ... Although there is no such built-in Hook, you can write it yourself. Declare a function called useOnlineStatus and move all the duplicated code into it from the components you wrote earlier:
🌐
Christhedeveloper
ww12.christhedeveloper.com › react-resuable-functions
christhedeveloper.com
July 11, 2017 - christhedeveloper.com · 2023 Copyright. All Rights Reserved. Privacy Policy
🌐
egghead.io
egghead.io › lessons › react-create-a-simple-reusable-react-component
Create a Simple Reusable React Component | egghead.io
[04:49] To review, to create a component that is reusable throughout your application and as composable as any other of the JSX that you have available to you is you create a function that has a capital letter as the first character.
Published   September 26, 2017
🌐
Medium
medium.com › @mrewusi › reusing-logic-in-your-react-apps-with-higher-order-components-70cdb8e7230a
Reusing logic in your React apps with Higher-Order Components | by Precious Nyarko | Medium
July 30, 2020 - Put differently, a HOC will basically take some component as an argument, (let’s call this the passed-in component from now on) and return a new component (let’s call this the enhanced component) that essentially wraps the passed-in component, with logic or functionality (via props), that it wouldn’t have had access to otherwise. So whenever we want a component to access some reusable logic, we run that component through a HOC and render new component that gets returned.
🌐
HackerNoon
hackernoon.com › the-three-types-of-reusable-react-components-37a6bf7c2d69
The Three Levels of Reusability in React | HackerNoon
July 9, 2018 - Developers frequently talk about the importance of reusing code. We talk about the DRY principle (Don’t Repeat Yourself), code reviews are rife with comments like: “can you encapsulate this into a function and reuse it on line 19”, and we frequently explain to product owners why it’s important that when we change something over here, it changes over there automatically.
Top answer
1 of 4
5

To reuse the functionality of useEffect and other functions, here you may use custom hook and cover the common functionality in the custom hook and re-use in component where you need.

ex.

import React, { useCallback, useEffect, useState } from "react";

// ----------------------------------  Custom Hook  -----------------------------

const useCustomFetch = ({someProp}) => {
    const [itemData, setItemData] = useState(null);

    const resolveSessionData = useCallback(() => {
        const data = database.getItemData(); // fetching data
        setItemData(data); // setting fetched data to state
    }, []);

    useEffect(() => {
        if (someProp) {
            resolveSessionData(); // or may be fetch data based on props
        }
    }, [someProp]);

    const addNewItem = useCallback(function (dataToAdd) {
        /**
         * write code to add new item to state
        */
    }, [])

    const removeExistingItem = useCallback(function (dataOrIndexToRemove) {
        /**
         * write code to remove existing item from state
        */
    }, [])

    return {
        itemData,
        addNewItem,
        removeExistingItem,
    }
}

// ----------------------------------  Component managing users  -----------------------------

const ComponentUser = ({someProp}) => {
  const {
    addNewItem,
    itemData,
    removeExistingItem
  } = useCustomFetch('users')

  const handleAction = useCallback(function (action, data) {
    if (action === 'add') {
        addNewItem(data) // ex. adding user
    } else if (action === 'remove') {
        removeExistingItem(data) // ex. removing user
    }
  }, [])

  return <div>
    {itemData.map(function () {
        /**
         * render items here // ex. listing users
         */
    })}
    <button onClick={handleAction}>
        Add / Remove
    </button>
  </div>;
};

// ----------------------------------  Component managing posts  -----------------------------

const ComponentPosts = ({someProp}) => {
    const {
      addNewItem,
      itemData,
      removeExistingItem
    } = useCustomFetch('posts') // re-using custom hook
  
    const handleAction = useCallback(function (action, data) {
      if (action === 'add') {
          addNewItem(data) // ex. add new post
      } else if (action === 'remove') {
          removeExistingItem(data) // ex. remove existing post
      }
    }, [])
  
    return <div>
      {itemData.map(function () {
          /**
           * render items here // ex. render posts
           */
      })}
      <button onClick={handleAction}>
          Activate Lasers
      </button>
    </div>;
};
2 of 4
1

Yes, it is correct way. There is no better way in React.

🌐
Medium
medium.com › backticks-tildes › reusing-react-component-logic-with-higher-order-component-3fbe284beec9
Reusing React Component logic with Higher Order Component | by Chinonso Johnson | Backticks & Tildes | Medium
June 20, 2018 - One of its primary functions is CONECT which accepts a component and returns a component connected to the Redux store, wrapping the one provided. It saves you the hassle of managing the logic connection to the store in multiple places in your app. ... In this article we will focus on code reuse and how we can use Higher Order Components as an alternative to inheritance
🌐
GeeksforGeeks
geeksforgeeks.org › reactjs › how-to-use-hocs-to-reuse-component-logic-in-react
How to use HOCs to reuse Component Logic in React ? - GeeksforGeeks
July 23, 2025 - }; return <WrappedComponent {...props} {...extraProps} />; }; // Simple component that displays props const DisplayPropsComponent = (props) => ( <div> <h1> {Object.entries(props).map(([key, value]) => ( <p key={key}>{`${key}: ${value}`}</p> ))} </h1> </div> ); // Enhanced component with extra props const EnhancedComponent = withExtraProps(DisplayPropsComponent); // Usage in App component function App() { return <EnhancedComponent someProp="This is some prop" />; } export default App; ops = (WrappedComponent) => (props) => { const extraProps = {extraProp: 'This is an extra prop!'}; return <Wrap
🌐
javascriptroom
javascriptroom.com › blog › how-can-i-use-a-function-from-another-file-in-react
How to Use a Function from Another File in React: Importing and Implementing Reusable Functions in Components
This keeps your project structure clean and makes functions easy to find. src/ ├── components/ │ ├── ProductCard.jsx │ └── CheckoutForm.jsx ├── utils/ # Dedicated folder for reusable functions │ ├── formatters.js # Date/currency formatting │ └── validators.js # Form validation logic └── App.jsx
🌐
Medium
medium.com › @matt_65849 › reusable-functions-in-react-keeping-it-dry-without-overdoing-it-7a34cc217762
Reusable Functions in React: Keeping it DRY (Without Overdoing It) | by Matthew Johns | Medium
March 27, 2025 - In the same spirit, developer Sandi Metz famously said: if your choice is between duplication and the wrong abstraction, choose duplication​. In other words, not all repetition is evil — it’s often cheaper to duplicate a few lines than to introduce a clever-but-fragile function that doesn’t truly fit all uses. Kent C. Dodds even advocates for AHA — “Avoid Hasty Abstractions” — suggesting you let similar code exist in two places until you’re sure how to generalize it​. In fact, sometimes the fastest way to fix a messy abstraction is to remove it and put the duplicated code back until a clearer pattern emerges​. So, what’s the takeaway? Aim for reuse when it genuinely reduces overall complexity, but don’t abstract too early.