Adopt a Pet! useHistory()

Front-End Engineer Career Path

React Part II React Router Adopt a Pet! Task #28

I’m importing useHistory, to receive history object.
It has history.goBack() function that moves the pointer in the history stack by -1.
Then I must use it as “Go Back” button event handler.
In the provided code from this Project, instead of directly giving reference to history.goBack to onClick event like this:

const history = useHistory();
<button className="button" onClick={history.goBack}>
          Go Back

there is code that first wraps it in another function called goBack() ,that calls history.goBack() and then passes this new function as event handler to onClick event:

const history = useHistory();

  const goBack = () => {

<button className="button" onClick={goBack}>
          Go Back

I can’t understand why we need to wrap history.goBack() to another function to pass it as event handler ? Because it works both ways :exploding_head:

I’ve seen similar things throughout CA lessons. I came to the conclusion that they are doing things like that to make the code they provide easier to understand for beginners.

I could be wrong of course, maybe there is a more technical reason behind it.

Without wrapper: onClick receives only goBack() function reference and loses this, so inside goBack() this is undefined (in strict mode, without strict mode its global object) ;

With wrapper: onClick literally runs history.goBack() , so goBack() has this referenced to history object.

But it works both ways, that’s why I’m wondering why they have wrapped it.
To go simpler , the question is: does goBack() function needs this === history to do its job or not :smiley:
I’ll check React Router docs anyways to learn newer version and answer will eventually pop up.

Thanks for your response.