So I have stumbled upon a React Hooks based component that uses objects to categorize various functions for readability.
For eg.
const MyComponent = (props) => {
const utilities = {
utility1: () => {
// ...some functionality
},
utility2: () => {
// ...some functionality
},
};
const renderers = {
renderer1: () => {
// ...some rendering logic
},
renderer2: () => {
// ...some rendering logic
return (
<span>{renderers.renderer1()}</span>
);
},
};
return (
// ...rendering logic
);
};
What I want to understand is why is renderer2
working correctly even when it calls renderer1
?
What I understand is that the object will be declared when the code is executed and the declaration is not complete till all properties are defined (this is just my noob understanding, I may be entirely wrong).
I would be really interested in knowing why this little bit of code works, especially why does it work correctly?
Also, on a side note, compared to Class-based components, I feel Hooks-based components are not very readable, and this approach tries to mitigate the problem. So I was wondering if this is the best way to make a Hooks-based component readable, or if there are other better approaches for the same?