What are React functional components?

A React functional component is a simple JavaScript function that accepts props and returns a React element.

After the introduction of React Hooks, writing functional components has become the ​standard way of writing React components in modern applications.

svg viewer

React Hooks were introduced in React 16.816.8 – they allow you to use state without writing class components.

Code

Below is an example of two functional components: App and MyComponent.

MyComponent takes props as an argument and returns a React element. The App functional component uses MyComponent and returns a React element.

import React from "react";
/**
 * A functional component (ES6 arrow) called MyComponent
 * that takes props as argument and returns a React
 * element.
 */
const MyComponent = (props) => {
  return (
    <div>Hello {props.name}!</div>
  );
}

/**
 * A functional component called App that returns a 
 * React element.
 */       
function App () {
  return (
    // Passing the name when using the component
    <div>
      <MyComponent name='World'/> 
      <MyComponent name='Educative'/>
    </div>
  );
}

export default App;

If you want to read more on components, state, and lifecycle methods check out, “What is a React component?”.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved