DEV Community

JesseNReynolds
JesseNReynolds

Posted on

React Functional vs Class Components Part 1: Props

The Times, They are a Changin'

If you, like me, learned React with class components doing all the lifting you may be wondering what's new with these functional components and their hooks that people are talking about? Maybe when you were learning React the curriculum you were following said to use functional components when you didn't need state or access to lifecycle methods. Now you're looking at React again and people are talking about hooks and how functional components are SO MUCH BETTER. What happened?

In React 16.8, hooks were introduced. Don't worry, though, the stuff you learned about React is still true. There's no big shakeups to how class components work, though you may run into a deprecated method here and there. So don't worry, you didn't just inherit a huge technical debt on that side project you used react for a while back and want to add a feature to now.

React's bread and butter are props and state, we'll address how functional and class components deal with props in this article, then we'll address state, and finally lifecycle methods in their own posts.

Props

Just as a refresher, when you pass props to a class component it might look like...

<OurComponent color={'purple'}/>
Enter fullscreen mode Exit fullscreen mode

Good news, no change there! It doesn't matter if you're declaring a class or functional component, you pass it props the same way.

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.color}</h1>;
  }
}
Enter fullscreen mode Exit fullscreen mode

In a class component props are handled by the constructor method from React.Component and we reference them with this.props.color..

function OurComponent(props) {
  return <h1>Hello, {props.color}</h1>;
}

Enter fullscreen mode Exit fullscreen mode

In a functional component, we accept props as an argument to the top level function, and can reference the color key in the props object with props.color.

Next week, we'll tackle state! Be excited, because we're going to meet our first functional hooks.

Top comments (0)