Functional Component Overview in React

Matthew Garcia

While class syntax gives the most control over a React component, it’s often more verbose than it needs to be.

Creating a functional component

A functional component is simple to define; it’s just a function that returns a valid React element.

const MyComponent = () => (
  <div>This is my component.</div>

Compared to the equivalent in class syntax, it’s easy to see the appeal of this shorthand.

class MyComponent extends Component {
  render() {
    return (
      <div>This is my component.</div>

Using props

Like class components, functional components can take props. Passing them in is identical.

<Nametag name="Noman" />

And they can be accessed as the first parameter.

const Nametag = ({name}) => (
  <div>{`Hi, my name is ${name}!`}</div>

The downside to functional components

They’re pretty much just a barebones render function, so some of the neat things you can do with class components are off the table. No state, no refs, no lifecycle functions. Fox only, Final Destination.

While this may seem like a deal-breaker, the fact of the matter is that many React components end up never using these things, and use props as their sole source of data. This is especially true in applications utilizing Redux or Relay.

  Tweet It

🕵 Search Results

🔎 Searching...