DEV Community

Visali Nedunchezhian
Visali Nedunchezhian

Posted on

ReactJS Functional Components

In ReactJS, functional components are a core part of building user interfaces. They are simple, lightweight, and powerful tools for rendering UI and handling logic. Functional components can accept props as input and return JSX that describes what the component should render.

Example:

import React, { useState } from 'react';

function App() {
  const [message, setMessage] = useState("Hello World!");

  return (
    <div style={{ textAlign: "center", marginTop: "50px" }}>
      <h1>{message}</h1>
      <button onClick={() => setMessage("Welcome to React!")}>
        Click Me!
      </button>
    </div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

When a functional component receives input and is rendered, React uses props and updates the virtual DOM to ensure the UI reflects the current state.

  • Props: Functional components receive input data through props, which are objects containing key-value pairs.
  • Processing Props: After receiving props, the component processes them and returns a JSX element that defines the component's structure and content.
  • Virtual DOM: When the component is rendered, React creates a virtual DOM tree that represents the current state of the application.
  • Re-rendering: If the component's props or state change, React updates the virtual DOM tree accordingly and triggers the component to re-render.

Functional Component with Props

In React, a functional component with props is a JavaScript function that receives an object called props as its argument. Props (short for “properties”) are used to pass data from a parent component to a child component.

This allows components to be dynamic and reusable, as the data displayed can change based on what is passed in.

Example:

import React from 'react';
import ReactDOM from 'react-dom';

// Functional component with props
function Greet(props) {
  return <h2>Hello, {props.name}!</h2>;
}

// Rendering the component and passing a prop
ReactDOM.render(
  <Greet name="Aditi" />,
  document.getElementById('root')
);
Enter fullscreen mode Exit fullscreen mode

Output:

Hello, Aditi!
Enter fullscreen mode Exit fullscreen mode

When to Use ReactJS Functional Components

Functional components should be used whenever possible because they are simpler, easier to test, and more performant than class components. However, there are a few cases where functional components may not be suitable:

  • Stateful components: Functional components cannot hold state on their own. Therefore, if you need to maintain state within your component, you may need to use a class component.
  • Lifecycle methods: If you need to use lifecycle methods such as componentDidMount, componentDidUpdate, or componentWillUnmount, you will need to use a class component.

Top comments (0)