React supports both class and function components. All React files have an import React from ‘react’
statement at the top. When creating a class component (like so: class MyClassComponent extends React.Component ...
), there is an explicit mention of which class this class instance extends from. However, when declaring a function component (const MyFunctionComponent = () => ()
), it isn’t being explicitly said “hey this is a React component by the way.”
For all we know, this could be a function in plain JavaScript. How then, does React recognize functions as function components?
Here is the code for the isValidElement() function. In a nutshell, they check if it is an object (functions are objects) with a $$typeof
of the REACT_ELEMENT_TYPE
Symbol.
Beyond that though, it doesn't really matter if it is a normal function or not. For the most part, even if I make some random function, as long as it has a render()
function, it'd be usable as a React element. I'm not sure if they have checks for missing lifecycle functions or not, but if they do, then it would work (if they don't, it'd throw errors).
When it comes to JavaScript "inheritence", it always just boils down to if the shape of the object matches the expected shape.
It doesn't do that, every function is valid, if it returns a valid type. However, React doesn't check statically if a function will return something valid, so it just runs it, if it's a function. In newer React versions the return value can be nearly everything. Arrays work now, strings also. Currently React does support the following types as return values:
So, unless you don't return undefined, it should work, but as said, it will execute it always if it is a function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With