How to Create Functional Components in React

Cristian Salcescu
Frontend Essentials
4 min readJun 5, 2020

--

Photo by the author

Have you wondered how to create a component in React? To answer, it is as simple as creating a function returning an HTML-like syntax.

import React from 'react';function Counter({n}) {
return (
<div>{n}</div>
);
}
export default Counter;

Now let’s see what happened. Counter is a function that transforms a number into HTML. And if you look more carefully, Counter is a pure function. That’s right, the kind of function that returns the result based on its inputs and has no side-effects. This explanation comes with a new question. What is a side-effect?

In short, a side-effect is any modification on the environment outside the function or any read data from the outside environment that can change.

You may have noticed that I used the destructuring assignment syntax in the parameter list to extract out the n input number. That’s because components take as input a single object called “props” that has all the properties send to them. Here is how the n parameter can be set from any other component:

<Counter n={1} />

In a sense, this syntax can be imagined like a function call Counter({n: 1}). Isn’t that right?

--

--