How can I pass a function to parent component in React? [closed]

In my React project, I want to keep all my functions in a single file and then I want to use the functions where I need. I can pass via props but that way I can’t pass the function to parent components. Some people suggesting me to use context API. I can pass static data through context API but I don’t know how can I pass the function. Can any one of you give me a possible solution or idea for this?

Answer

Let’s say you have a utils.js file as below

export function add(a, b) {
  return a + b;
}

You can then import that function in a component like so

import { add } from './utils';

const result = add(2, 3);

function App() {
  return <div>{result}</div>
};