Call function React js

In React, you can call a function in various ways depending on the context.

Here, I’ll provide examples of calling functions in different scenarios.

Function Component :

In this example, the myFunction is called when the button is clicked. The onClick event handler is used to associate the function with the button click event.

import React from 'react';

function MyComponent() {
  const myFunction = () => {
    console.log('Function called!');
  };

  return (
    <div>
      <button onClick={myFunction}>Call Function</button>
    </div>
  );
}

export default MyComponent;

Class Component :

For class components, you define functions within the class, and you can refer to them using this. Again, the onClick event is used to trigger the function.

import React, { Component } from 'react';

class MyClassComponent extends Component {
  myFunction() {
    console.log('Function called!');
  }

  render() {
    return (
      <div>
        <button onClick={this.myFunction}>Call Function</button>
      </div>
    );
  }
}

export default MyClassComponent;

Passing Function as Props :

You can pass a function as a prop to a child component and call it from there.

In this example, ChildComponent receives myFunction as a prop and calls it when the button is clicked.

import React from 'react';

function ParentComponent() {
  const parentFunction = () => {
    console.log('Function in parent called!');
  };

  return (
    <div>
      <ChildComponent myFunction={parentFunction} />
    </div>
  );
}

function ChildComponent({ myFunction }) {
  return (
    <div>
      <button onClick={myFunction}>Call Parent Function</button>
    </div>
  );
}

useEffect Hook (Functional Component) :

Here, useEffect is a React hook that allows you to perform side effects in function components. The function passed to useEffect is called when the component mounts and on subsequent updates (in this example, it only runs once due to the empty dependency array []).

import React, { useEffect } from 'react';

function MyEffectComponent() {
  useEffect(() => {
    // This function is called on component mount and update
    console.log('Function in useEffect called!');
  }, []);

  return <div>Component with useEffect</div>;
}

export default MyEffectComponent;

Choose the method that best fits your use case based on the component type and the desired behavior.

About the author

Full-stack web developer with great knowledge of SEO & Digital Marketing. 7+ years of experience in Web Development.

Leave a Reply