⚛️ React Q101 / 113

How do you create a React functional component?

AI-Powered Answer ✓ Answered

React functional components are JavaScript functions that return React elements. With the introduction of Hooks, they have become the primary way to build components, offering a simpler syntax and powerful capabilities for managing state and side effects without needing class components.

Basic Structure

A functional component is a plain JavaScript function that accepts a single 'props' object argument with data and returns a React element. The simplest form uses an arrow function, though traditional function declarations also work.

jsx
import React from 'react';

const MyComponent = (props) => {
  return (
    <div>
      <h1>Hello, {props.name || 'World'}!</h1>
      <p>This is a functional component.</p>
    </div>
  );
};

export default MyComponent;

Alternatively, using a standard function declaration:

jsx
import React from 'react';

function AnotherComponent(props) {
  return (
    <div>
      <h2>Welcome, {props.user}!</h2>
    </div>
  );
}

export default AnotherComponent;

Functional components receive data through a single argument called props (short for properties). You can destructure props for cleaner code.

jsx
import React from 'react';

const WelcomeMessage = ({ name, greeting = 'Hello' }) => {
  return (
    <p>{greeting}, {name}!</p>
  );
};

export default WelcomeMessage;

Managing State with `useState`

Functional components can manage their own internal state using the useState Hook. This hook returns an array with two elements: the current state value and a function to update it.

jsx
import React, { useState } from 'react';

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <button onClick={() => setCount(count - 1)}>Decrement</button>
    </div>
  );
};

export default Counter;

Performing Side Effects with `useEffect`

The useEffect Hook allows you to perform side effects (like data fetching, subscriptions, or manually changing the DOM) in functional components. It runs after every render by default, but you can control when it runs using its dependency array.

jsx
import React, { useState, useEffect } from 'react';

const Timer = () => {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds(prevSeconds => prevSeconds + 1);
    }, 1000);

    // Cleanup function runs when the component unmounts or before re-running the effect
    return () => clearInterval(interval);
  }, []); // Empty dependency array means this effect runs once on mount and cleans up on unmount

  return (
    <div>
      <p>Timer: {seconds} seconds</p>
    </div>
  );
};

export default Timer;

Key Characteristics and Benefits

  • Simpler Syntax: Generally less boilerplate than class components.
  • Readability: Often easier to read and understand, especially with Hooks.
  • Hooks: Enable state and lifecycle features within functions, eliminating the need for classes.
  • Performance: Can be optimized by React internally in some scenarios (e.g., with memoization without shouldComponentUpdate).
  • Testing: Often easier to test due to their functional nature.