0

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?

2

1 Answer 1

1

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 not so. A variable declaration happens ahead of time - at compile time, before any code actually has had a chance to run. The assignement to a variable happens at runtime though. This includes evaluating the value being assigned.

So in the case you're talking about, when the object being assigned to renderers is being evaluated, the renderers variable is actually already declared.

Also, you have to consider the fact that renderers.renderer1() is not actually being called as part of the evaluation of this object - but only later on when renderers.renderer2() is actually be called, at which point both the object evaluation and the assignment will have completed, and thus renderers.renderer1() will be what you expect it to be.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh right! The fact that it is called later on makes SO much sense! Like, that line clicked it all together in my head. Thanks a lot :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.