React Hooks, introduced in React 16.8, present us with a fundamentally new approach to coding. Some may think of them as a replacement for lifecycles or classes, however, that would be wrong. Like trying to translate a word from another language, sometimes you’re facing a completely new entity, which seems identical on the surface but is very different semantically and can’t be treated as equivalent. 

React not only changed the approach from OOP to Functional. The method of rendering has changed in principle. React is now fully built on functions instead of classes. And this has to be understood on a conceptual level. 

In fact, to fully grasp the idea, you’ll have to change your whole thinking process when coding in React. Hooks call for a more declarative approach, meaning that it is strictly mathematically logical, in contrast to imperative programming that is more lax in this sense. 

Before, when working with classes, you would have a state object and its change would trigger the re-render. This was a global object within the component (class) with every instance having a link to this state. It’s important to understand that this object is a singleton and it will be the same in each render. 

This can be clearly seen in the example. 

React import

First, we use a class to define a component with the starting value of zero. We create a button component that triggers a render by onClick, changing  setState to value + 1. 

In practice, this means that if you open the page and quickly click the button a few times, you’ll see that in five seconds a number appears in the console equivalent to the number of times you clicked the button. This shows us that all the renders refer to a single object. 

If you compare this to the functional approach with Hooks, it’s very similar to functions in JS. Hooks produce a new environment on each render, presenting you with a completely new set of data. 

React takes into account all changes in state Hook and calls on the function-component one more time, thus all the variables, functions (including those received from Hooks) will be in closure and they will be different for each render. This is also clearly seen in the example.

import react from react

We are using two Hooks:useState and useEffect, to implement similar functionality. With the default state set to zero, each onClick of the button triggers a change of state to state + 1.

However, in this example, if you click the button a few times while the render is in progress, in five seconds you’ll see a zero. This means that the meaning of the state is in closure and on each render you’ll get a different state as well asuseEffect. 

This is important to understand and use in your code. If you’re still not sure if you need to use Hooks when coding in React, go back to the drawing board, learn what React Hooks really constitute, what are the benefits, and at least give it a try. 



Source link

Write A Comment