Important Function Syntax in ReactJS

We can declare any function in regular function syntax. Which is basically a JavaScript way to write any function.

Regular function in ReactJS

  • Declare a function with a name
function App() {

  return (
    <div >
      <h1>This is a regular function of JavaScript in React</h1>
    </div>
  );
}

Here, we have declared a regular function with the name of App. It doesn’t have any parameters in it. and after the function declaration, we have returned a <div>...<div>. And inside this section, whatever we write, will be visible to the browser. We have written a <h1> tag.

You might wonder how are we able to write some HTML tags in JavaScript. Truth is, we can’t. It might look like HTML. But it is not. These are JSX syntaxes. To know more about JSX, Please read this article.

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



function App() {

  return (
    <div >
      <h1>This is a regular function of JavaScript in React</h1>
    </div>
  );
}

export default App

After running the server by, npm start,

Alternative function syntax (Arrow function) in reactJS

Now, What is an arrow function?

Well, it is almost like a variable declaration but with an equal sign and a greater sign to form an arrow. With the arrow function, developers can write much cleaner code compared to the regular function declaration. It comes with the ES6 version of JavaScript.

Write an arrow function in ReactJs

To write an arrow function instead of a regular one, please follow the below procedures,

  • Replace function with const,
const
  • Give a name to it(it will be the name of the function)
const App

In our case, the name of the function will be App.

  • Assign parameter(s) if there is some after adding an equal sign; else just add empty brackets
import React, { useState, useEffect } from "react";



const App = ()

We don’t have any parameters, hence we have just added empty brackets.

  • Write an equal sign and a greater sign to form an arrow after the brackets
import React, { useState, useEffect } from "react";



const App = ()=>
  • Then write curly braces.
import React, { useState, useEffect } from "react";



const App = () => {

}

export default App
  • And then return something from this function
import React, { useState, useEffect } from "react";



const App = () => {

  return (
    <div >
      <h1>This is a regular function of JavaScript in React</h1>
    </div>
  );
}

export default App

In our case, we are returning a <div> here with some content in it.

After running the server,

As we can see, we are getting similar results as the previous one. But now instead of using a regular function syntax, we have used a different one, the Arrow function.

This is how we can declare a function in an alternative way.