Why is it called a functional component?
https://softwareengineering.stackexchange.com/questions/399024
-
02-03-2021 - |
문제
A quick google search shows that the question I have has not been asked directly, and so I ask it here. For what its worth, I am learning react, and I come from a C++ background, where as far as I know, "functional components" are not a thing.
Taking from a tutorial, this seems to be a barebone example of a functional component
import React from 'react';
function App()
{
const greeting = 'Hello Function Component!';
return <h1>{greeting}</h1>;
}
export default App;
It just looks like a function to me, and yet in react, it is referred to as a functional component.
- Why is the terminology, "functional component" used?
- Why not "Component Function"?
- If I simply called this a function, would react developers be confused?
Thanks.
해결책
Actually, the React documentation calls them function components.
Up until recently, there have been two ways to create React components: using a class, or using a function. Such functions were called stateless function components. A React stateless functional components was basically a pure function: same inputs (i.e. props) => same outputs (i.e. rendered output).
With the introduction of hooks in React 16.8 these functions are no longer pure, because they hold some state: same inputs => different outputs.
Here is an example of a function component which is not stateless.
import React, { useState } from 'react';
function App() {
const [greeting, setGreeting] = useState('Hello Function Component!');
const onClick = (event) => {
setGreeting('Hello hooks!');
}
return <h1 onClick={onClick}>{greeting}</h1>;
}
export default App;
The component above renders a <h1>Hello Function Component!</h1>
until you click it, then it will always render <h1>Hello hooks!</h1>
.
The variable greeting
is called state variable, and the React function component manages to keep track of that variable if you follow the hooks rules. I think the React function components hold state by using closures, and they need the order of execution of hooks to stay the same between renders.
To sum it up, I think that calling this component just "function" is fine, as long as you keep in mind that it's not pure.