20 Feb 2024




Beginner

In React.js, Functional components are JavaScript functions that accept props as arguments and return React elements. In the past, before React 16.8, functional components were stateless and primarily used for rendering UI based on props passed to them.

However, with the introduction of React Hooks in React 16.8, functional components gained more power and flexibility. Developers can now use hooks like useState, useEffect, useContext, and others to add state and side effects to functional components, effectively making them more capable and powerful.

Example of functional component:

import React, { useState } from 'react';

// Functional Component with State
function Counter() {
  const [count, setCount] = useState(0);

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

export default Counter;

In the example above, Counter is a functional component that uses the useState hook to manage a count state. When the button is clicked, the setCount function is called to update the count state, triggering a re-render of the component with the updated count value.

Functional components offer a simpler and more concise syntax compared to class components, and they are now the preferred way to write components in React.js due to their advantages and the addition of hooks.

reactjs
functional-component