Home > other >  How can I share one same function between two components far away
How can I share one same function between two components far away

Time:10-19

I have one function funA on component A, ComponentA and another component B, componentB. Now, I want to ComponentB to use this same function, funA.

How can I share this funA to ComponentB?

I was thinking about redux, but redux doesn't suggest passing a non-serializable value, like a function, to a state.

What's the solution for this?

Edit: the funA persisting some states of componentA, I want to keeping these states when using on componentB. I was trying to create a custom hook, however the hook is a individual closure for each time call the hook, which means I cannot hold the state.

CodePudding user response:

Put the function in its own file and import it in both places:

// fun-a.js
export function funA () {
  return "woo";
}
// component-a.js
import { funA } from './fun-a.js';

export function ComponentA (props) {
  return (
    <div>{funA()}</div>
  );
}
// component-b.js
import { funA } from './fun-a.js';

export function ComponentB (props) {
  return (
    <div>{funA()}</div>
  );
}

CodePudding user response:

Put this data from a ComponentA to redux store. If you need this data from store formatted by some function "funA", create selector:

export const funASelector(store) {
  // do something with data from store and return the result
}

Or if you don't have redux or don't whant to use it, use react context to store data from ComponentA and provide this data to ComponentB. When you receive data at ComponentB, call the function to format data

  • Related