...and then the hooks update was released. Looks like someone wasn’t supposed to stay dumb forever :-)
In this article, I will talk about my experiences with them and discuss the key differences between these two that I came across.
React.Component(inheritance) and give the component access to
React.Component's functions. This class component should have an only required render() method further to return a React element and call it instead of implementing its own render logic.
Suppose you want to handle some event on the click of a button. Your event handler will be something like this:
... and if this is how you call the event handler:
You will get
this value as
undefined , this is because the
handleClick() has lost its component object or
this value, i.e. inside the method it cannot identify
this reference of the component. Now, this is what I meant when I said it depends on how the function is invoked. Therefore, in order to get the value of
this inside the function we need to either:
2. Or use an arrow function
a) As a callback:
b) In the event handler
So, that’s how things work in class. Now let’s see how it works with hooks.
In functional components, it's super easy to work because the curse of using this everywhere you use your local variable or call functions doesn't exist. Therefore, no significant use of arrow functions as well. With less code compared to class, it's already a win.Now how does this ‘dumb’ function gets state? Simple. Through the
useStatehook. Everything else is exactly the same as that of the class.
React class has lifecycle methods which are a series of events that happen from the time component is mounted to till it is unmounted.
For the component these series of events can be divided into 3 parts :
Now that must make you wonder if
render() is a lifecycle method or not. Of course it is. It occurs between mounting of the component and its update.
Corresponding to these three events, we have three common lifecycle methods.
Coming to functions, we have one hook that does all these lifecycle functions-
Interesting isn’t it?
But how does it have all 3 lifecycle functions in one?
Let’s find out.
useEffect() takes two arguments: a callback function and an array of dependencies. The second argument is more interesting. When an empty array is given, it means you want to run an effect and clean it up only once, thereby achieving
unmount, but on passing a state variable in the array calls the
useEffect() each time the state variable value changes, thus causing an update.
The demo for the same using functional components is given here, if you're interested to see how it works.
Hope this article helped you, thanks for reading.