Bhargava Macha
Bhargava Macha

Reputation: 87

Do embedded react hooks have a performance degradation compared to single use hooks?

I have a hook (let's say useBook) that needs 3 lines of code to be used. If I wrap it in another hook (let's say useBookWithParams) which needs only 1 line of code and calls useBook and returns the data, would using useBookWithParams cause any performance degradation compared to useBook? I am trying to decide b/w code readability and performance tradeoffs. (Assume useBook's result is cached and abstracted away in the implementation)

Upvotes: 1

Views: 83

Answers (1)

Drew Reese
Drew Reese

Reputation: 202836

If I'm understanding your post correctly you are basically asking if there's a significant performance hit between

export const myFunction = () => {
  // line 1 of code
  // line 2 of code
  // line 3 of code
}

...

myFunction();

and

const innerFunction = () => {
  // line 1 of code
  // line 2 of code
  // line 3 of code
}

export myFunction = () => innerFunction();

...

myFunction();

No, there won't be much difference in performance between the two. The second version will need to call/push innerFuction onto the stack, execute the code, then return/pop the result, but this is negligible in the grand scheme of your React app running.

Regarding readability/maintainability, that is subjective. IMO if the code/logic for the "inner function" is defined and used in only the one place, it's not worth factoring out into a function. This stems from the Don't Repeat Yourself (DRY) principle.

To specifically answer your question:

would using useBookWithParams cause any performance degradation compared to useBook?

No, I don't believe there'd be any performance degredation. I think you'd be hard-pressed to even achieve any measurable difference in performance other than under stress test conditions where you are calling the function in a loop as quickly as the system allows.

Upvotes: 1

Related Questions