Utils.js with latest Javascript ES6 syntax

Create the Utils.js file like this with multiple functions, etc

const someCommonValues = ['common', 'values'];
    
export const doSomethingWithInput = (theInput) => {
   //Do something with the input
   return theInput;
};
    
export const justAnAlert = () => {
   alert('hello');
};

Then in your components that you want to use the util functions, import the specific functions that are needed. You don't have to import everything

import {doSomethingWithInput, justAnAlert} from './path/to/Utils.js'

And then use these functions within the component like this:

justAnAlert();
<p>{doSomethingWithInput('hello')}</p>
Answer from Fangming on Stack Overflow
🌐
React
react.dev › learn › sharing-state-between-components
Sharing State Between Components – React
Make the Accordion component pass a hardcoded value of isActive (for example, true) to both panels: ... import { useState } from 'react'; export default function Accordion() { return ( <> <h2>Almaty, Kazakhstan</h2> <Panel title="About" isActive={true}> With a population of about 2 million, Almaty is Kazakhstan's largest city.
Discussions

Moving/ share functions between components - React.js
There are functions (I leave a comment there), which I want to use in another component, that’s why I want to move the function to separate folder like “utils”. Basically, I want to share functionality between components. Go to repo Go to view The component: import React, { useEffect, ... More on sitepoint.com
🌐 sitepoint.com
0
July 26, 2019
The most challenging thing for me about React is sharing state variables between components.
I don’t think people should be recommending state libraries and instead OP needs to understand the pattern of lifting state and managing state with just react. Edit: incorrectly referred to lifting state as hoisting More on reddit.com
🌐 r/reactjs
102
118
June 27, 2023
React sharing method across components - javascript
0 React share all methods inside a function component that might interact with the state between another function component More on stackoverflow.com
🌐 stackoverflow.com
React share all methods inside a function component that might interact with the state between another function component
I'm trying to share ALL the methods in a function component between another function component, even if the method interacts with the state, here's what I've got working so far: // App.js import Re... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GitHub
gist.github.com › bradparker › a9b638c02891173ddf3a
Sharing behaviour between React components · GitHub
So higher order components are functions which take in React components as input and / or return a React component as output. With that in mind we can write a function which takes a component and returns a new component which renders the original ...
🌐
Braingu
braingu.com › news › share-react-component-logic
Sharing Logic Between Components in Different React Renderers · BrainGu
This article discusses how to use a custom hook to share logic between two components; one component targeting react-dom to render HTML and another component that uses the react-pdf renderer primitives for use in creating a larger PDF component.
🌐
DEV Community
dev.to › sonaykara › reactjs-sharing-state-between-components-52pg
React.js : Sharing State Between Components - DEV Community
January 2, 2025 - To synchronize the state of two components, a shared state should be lifted to their nearest common parent and passed down to both components as props. Let's transfer the isActive state to the parent component and add isActive to the Panel's ...
🌐
Medium
medium.com › @zachlandis91 › react-share-global-data-between-components-without-props-9f24abbcf208
React: Share “Global” Data Between Components Without Props | by Zach Landis | Medium
March 20, 2023 - This is because all elements created in React are JavaScript objects. As a result, passing data into a component is done by creating properties and values for the object.” · When you pass a prop from one component to the other, the receiving component has access to the data that was passed along. This can occur down the App Tree simply by passing the prop through as shown in the gif above. Props can also be sent back up the App Tree with the use of passing callback functions as props and then calling the function in the receiving component.
🌐
SitePoint
sitepoint.com › javascript
Moving/ share functions between components - React.js
July 26, 2019 - There are functions (I leave a comment there), which I want to use in another component, that’s why I want to move the function to separate folder like “utils”. Basically, I want to share functionality between components. Go to repo Go to view The component: import React, { useEffect, ...
Find elsewhere
🌐
Codedamn
codedamn.com › news › react js
How can I share data between components in React.js?
October 18, 2023 - If the child components need to modify the state, pass down callback functions via props. What is the Context API? React’s Context API provides a way to share values (data or functions) between components without having to explicitly pass props through every level of the component tree.
🌐
The Odin Project
theodinproject.com › lessons › node-path-react-new-passing-data-between-components
React - Passing Data Between Components
By now you should be starting to understand just how powerful React and reusable components can be, but you may be left wondering ‘How can I share information between components?’ or ‘Am I able to customize the behavior of my components each time I use them?’. In this lesson, we will learn about React props (short for properties) and how to use props to pass data between components.
🌐
DEV Community
dev.to › betula › sharing-react-hooks-stateful-logic-between-components-1g3o
Sharing React hooks stateful logic between components - DEV Community
January 21, 2021 - When you want to separate your ... some of state parts or control functions to another component your need pass It thought React component props....
Top answer
1 of 1
1

Why not create a custom hook with as much shared logic as possible that returns all of your data and needed methods?

For example:

/* color.jsx */

export function useColor() {

  // Our shared state:
  const [state, setState] = useState({
    color: 'No color picked yet',
  });

  // Our methods:
  const changeColorToRed = () => {
    setState({
      color: 'red',
    });
  };

  const changeColorToGreen = () => {
    setState({
      color: 'green',
    });
  };

  const changeColorToBlue = () => {
    setState({
      color: 'blue',
    });
  };

  return {
    state,
    changeColorToRed,
    changeColorToGreen,
    changeColorToBlue,
  }
}

So basically, we'll have this shared hook containing a shared state and methods,
and we'll return everything we want to use in the relevant comps.

For example:

/* FooColor.jsx */

const FooColor = () => {
  const { state, changeColorToRed, changeColorToGreen, changeColorToBlue } = useColor();

  return (
    <div>
      <div style={{ fontSize: 30 }}>Foo</div>
      Foo Color: {state.color}
      <br />
      <button onClick={changeColorToRed}>Change foo color to red</button>
      <button onClick={changeColorToGreen}>Change foo color to green</button>
      <button onClick={changeColorToBlue}>Change foo color to blue</button>
    </div>
  );
};

Then you can import and use it in the exact same way in BarColor.

In this example we get a clean result without the need for useRef or even props of any kind in this case.

For more info, you can check out the documentation about custom hooks.

Also, the use-case here is a little vague so I hope that I understood your needs correctly.
Let me know if you need some more help with this.


Update:

If we need 2 separate states for each component color,
we can simply manage separate states in the shared hook.

Example:

  // Either like this:
  const [fooColor, setFooColor] = useState('No color picked yet');
  const [barColor, setBarColor] = useState('No color picked yet');

  // Or like this (my personal preference):
  const [state, setState] = useState({
    fooColor: 'No color picked yet',
    barColor: 'No color picked yet',
  });

  // Then we can add a parameter in order to avoid function duplication:
  const changeColorToRed = (comp) => {
    switch (comp) {
      case 'foo':
        setState({
          // Spread the existing contents of the state (`barColor` in this case):
          ...state,
          fooColor: 'red',
        });

      case 'bar':
        setState({
          ...state,
          barColor: 'red',
        });

      default:
        console.error('Non-existent comp passed');
    }
  };
🌐
Pluralsight
pluralsight.com › tech insights & how-to guides › tech guides & tutorials
How to Use React Context to Share Data between Components | Pluralsight
April 24, 2024 - A workaround for that is to have a dedicated Context/Provider for each functional section that share data between its own components. Then you will reduce the number of components rendering as you will only have updates on sub-trees of your app. In this guide, we explored how we can easily use React Context instead of passing down props to share data between components.
🌐
Bekk Christmas
bekk.christmas › post › 2017 › 07 › share-logic-between-components!
Share logic between components! | Bekk Christmas
November 7, 2024 - Now, wouldn't it be cool to have a way to share those concerns in a declarative React way? One way of doing just that is by means of something the community called higher order components (or HOCs for short). Simply put, an HOC is a function that accepts a component as an argument, and returns a new component that wraps that component.
🌐
C# Corner
c-sharpcorner.com › article › how-to-share-data-between-components-in-react
How To Share Data Between Components In React
October 26, 2021 - Props data is shared by the parent component and Child component cannot be changed as they are read-only. ... import './App.css'; import Parent from './Modules/parentChild/parent-component' import 'bootstrap/dist/css/bootstrap.min.css'; function App() { return ( <div className="App"> <Parent/> </div> ); } export default App; ... import React from "react"; import Child from "./child-component"; const Parent = () => { const dataList = [{ name: "Robert", age: 21, role: "Test", }, { name: "Sat", age: 21, role: "Test", }, { name: "mani", age: 20, role: "Software", }, ]; return ( <div> <div class="row m-4 "> <h3>Parent To Child</h3> <Child dataList={dataList} /> </div> </div> ); }; export default Parent;
🌐
Squash
squash.io › sharing-state-between-two-components-in-react-javascript
Sharing State Between Two Components in React JavaScript
April 8, 2024 - In this example, we create a MyContext object using the createContext function from React. The ParentComponent wraps its child components with the MyContext.Provider component and passes the count state and incrementCount function as the value prop. The ChildComponent uses the useContext hook to access the shared state and function from the context. The context API provides a convenient way to share state between components without the need for props drilling.
🌐
Medium
medium.com › actived › how-to-share-state-between-multiple-components-without-passing-them-in-props-or-using-a-library-224480a94cf1
How to share state between multiple components without passing them in props (React, Context API). | by John Doe | Active Developement | Medium
October 31, 2022 - Now, lets imagine a component named “RecipesList” which only renders the recipe details, we will pass the shared state “recipes” in its props and also the function “onRemoveRecipe” which in turn will be passed down to the props of the component “RecipeCard” since it also needs to be able to remove a component.
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-share-state-across-react-components-with-context
How To Share State Across React Components with Context | DigitalOcean
July 22, 2020 - React context is an interface for sharing information with other components without explicitly passing the data as props. This means that you can share information between a parent component and a deeply nested child component, or store site-wide data in a single place and access them anywhere ...