Flat Preloader Icon

Functional Components

Functional components in React are a simpler way to write components that only render UI and do not have their own state or lifecycle methods. These components are essentially JavaScript functions that take in props and return React elements.

Basic Functional Component

				
					import React from 'react';

function Greeting(props) {
  return <h1>Hello, {props.name}!</h1>;
}

export default Greeting;

				
			

Using Hooks with Functional Components

With the introduction of React Hooks in version 16.8, functional components can now manage state and side effects. The most commonly used hooks are useState and useEffect.

1. useState Hook

The useState hook allows you to add state to a functional component:
				
					import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

export default Counter;

				
			

2. useEffect Hook

The useEffect hook allows you to perform side effects in functional components. It can be used for things like fetching data, updating the DOM, and setting up subscriptions:
				
					import React, { useState, useEffect } from 'react';

function Timer() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setCount(prevCount => prevCount + 1);
    }, 1000);

    return () => clearInterval(interval); // Cleanup on component unmount
  }, []);

  return <h1>{count} seconds passed</h1>;
}

export default Timer;

				
			

Advantages of Functional Components

  1. Simplicity: Functional components are easier to read and write.
  2. Performance: They may offer performance benefits due to less overhead compared to class components.
  3. Hooks: With hooks, functional components can now handle state and side effects, making them almost as powerful as class components.

Key Points

  • No ‘ this ‘ Keyword: Functional components do not use the this keyword, which can simplify your code and reduce potential bugs.
  • Stateless to Stateful: Initially, functional components were stateless, but with hooks, they can now have state.
  • Reusability: Functional components encourage reusability and composability.