React Basics – Lets create a functional component – Part 2 of 2

In part 1, we set up a basic class based component. This time around, we will build out a functional component!

I have set up a very basic functional component below. Take a look at the code, and then we can walk through it.

function CityName(props) {
  return <h2>{props.city}</h2>;
}

function App() {
  return (
    <div>
      <h1> The cities in Michigan are: </h1>
      <CityName city="Ann Arbor" />
      <CityName city="Detroit" />
      <CityName city="Dearborn" />
      <CityName city="Grand Rapids" />
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById('root'));

As you can see, we have 2 basic functions, CityName() and App(). One simply returns an h2 with props.city, which we can assign every time we call the CityName function in our return. This can be done dynamically, but for this article I wanted to keep it simple. The last thing our component will do is render our App(), which will display it to the user. I went ahead and added the code to a pen on www.codepen.io, which displays the following:

As you can see, we have each of our cities displaying. With a functional component, you can build out as many functions as you need, which leads to it being straight forward and easy to read and understand. I personally find a functional component far easier to understand that a class based component, but this is all personal preference.

So I bet you are asking when to use a functional component vs a class based component. When should we pick this over the other? If you do not care about state or lifecycle methods, functional components are a good way to go. They are typically easier to read, which leads to an easier time debugging your code, and they are typically easier to test as well. This is because there is no hidden state or side effects. For each and every input, functional components have exactly one output.

While this is just a small example of what a functional component is, the sky is the limit with what you are able to do. If you have any questions about this, leave a comment below and I will respond back. Thank you for reading and have a wonderful day!

Leave a Reply