What is the correct syntax for a functional component in React?

Understanding the Syntax for a Functional Component in React

React.js, developed by Facebook, is a popular library for building complex, interactive user interfaces, especially single-page applications where you need a fast response and want to maintain a user’s state during their session. React allows developers to create large web applications which can change data, without reloading the page. The main purpose of React is to be fast, scalable, and simple.

One of the building blocks of a React application is a component. Components in React serve as the building blocks of your application's UI. They split the UI into reusable, independent pieces. In terms of defining components, there are mainly two types - Class Components and Functional Components.

Let's focus on Functional Components. As the name implies Functional components are those components that are basically just a JavaScript function. They accept arbitrary inputs (called ”props”) and return React elements which describe what should appear on the screen.

Functional components were introduced in React 0.14, these components have no state, no lifecycle methods and don't extend from React.Component.

There are three ways of defining a functional component in React:

1. Traditional function declaration:

function MyComponent() { 
  return <div />;
}

2. Fat Arrow function or ES6 Arrow function:

const MyComponent = () => { 
  return <div />; 
}

3. Anonymous function stored in a variable:

var MyComponent = function() { 
  return <div />; 
}

All these three ways are correct syntax for defining a functional component in React. They take in optional props as input and return the same result – JSX which transforms to HTML.

We should note that functional components are simpler and easier to test in comparison to class components. Yet, they have some limitations. Functional components are essentially pure functions, they respect the idea of immutability and they don't have their own context (this), so lifecycle methods can't be used within them.

With the introduction of Hooks in React 16.8, functional components are now able to accommodate any feature a class component can. Today, the trend seems to be moving towards using more functional components and hooks, as they are easier to reason about and they simplify the codebase in most of the cases.

Knowing how and when to use either component type will allow you to build applications that are easier to understand, test, and maintain.

Do you find this helpful?