Is there a bigger load to the component when directly using object destructuring on hooks like this?

Viewed 48

Consider doing this:

const { pathname } = useLocation()
const { param1, param2 } = useParams()
const { push } = useHistory()

instead of:

const location = useLocation()
const params = useParams()
const history = useHistory()

const { pathname } = location
const { param1, param2 } = params
const { push } = history

Implementation:

console.log(pathname, param1, param2)
push('/next-route')

Despite being shorter in syntax, does the object destructuring in the former case bring in all properties of an object first and then assign single property to a new variable? If that's how JS works, the case then it would mean a slightly bigger load to the component. If not, there is nothing to bother about. Right?

1 Answers

Is it a good practice to do

It's not a "good" practice nor is it a "bad" practice: it's just a way of writing code that modern JavaScript allows as an alternative to more verbose and hand-written object graph handling code. The same can be said of most language features (though some things, like eval and forEach, probably should be generally avoided).

Despite being shorter in syntax, does the object destructuring in former case bring in all properties of an object first and then assign single property to a new variable?

No.

It seems you think that returning an object from a function involves copying all members of that object - that is untrue: while that is what happens when you return a struct value in C, whereas in JavaScript object values can be thought of as always living on the heap and are passed by-reference, so there's no expensive object cloning going on.

So doing this:

const { pathname } = useLocation()

Is more like this:

const pathname = useLocation().pathname;

It is not the same as this (conceptually, under-the-hood):

const pathname = Object.assign( {}, useLocation() ).pathname;
Related