Functional components in ReactJs


  • Functional components

In React.js, functional components are a type of component that is defined using a JavaScript function. They are also sometimes referred to as stateless components or functional stateless components. Functional components were the primary way of creating components in React before the introduction of Hooks in React 16.8.

Here's a breakdown of key concepts related to functional components in React:

Function Declaration: A functional component is simply a JavaScript function that takes in props (if any) as an argument and returns React elements. The function name is typically written in PascalCase to follow React conventions.

function MyFunctionalComponent(props) {

return <div>Hello, {props.name}!</div>;

}

Props: Functional components receive data through props. The props (short for properties) object contains information passed down from a parent component. In the example above, the name property is accessed through props.name.

const App = () => {
  return <MyFunctionalComponent name="John" />;
};

No State: Originally, functional components were "stateless," meaning they couldn't manage their own state. They were mainly responsible for presenting UI based on the provided props. However, with the introduction of React Hooks, functional components can now manage state using hooks like useState.

import React, { useState } from 'react'; // Functional component with state using useState hook
function Counter() { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }


Lifecycle Methods: Functional components don't have lifecycle methods (such as componentDidMount, componentDidUpdate, etc.) like class components do. However, with the introduction of React Hooks, you can use useEffect to achieve similar effects.

import React, { useEffect } from 'react';

function MyFunctionalComponent() {
  useEffect(() => {
    // ComponentDidMount and componentDidUpdate combined
    console.log('Component has mounted or updated.');
    // Cleanup function (ComponentWillUnmount)
    return () => {
      console.log('Component will unmount.');
    };
  }, []); // Empty dependency array means this effect runs once after the initial render

  return <div>Hello!</div>;
}


Simplified Syntax: Functional components have a more concise and cleaner syntax compared to class components. With the advent of ES6 and arrow functions, defining functional components became even more concise.

// ES6 arrow function syntax const MyFunctionalComponent = (props) => { return <div>Hello, {props.name}!</div>; };





Post a Comment

Previous Post Next Post