David Rodenas PhD
1 min readAug 20, 2022

--

Hi Elisabetta.

It is just the other way around. Hooks are the way that React provides to deal with impurity in "functional" components. It wraps, and hides, impurity behind what seems pure functions.

The “functional” components are render functions that React calls each time that thinks that something may change. But functions do not store any state, we cannot keep track from one call to another, and we do not know what happen before. Here is when hooks enter, they have access to the React component state, and can store information there. We can say that they access to the hidden this.state visible from the “class” components.

Because of it, all hooks are impure, they store everything that they need in that external (and impure) state outside the function scope. For example:

  • useRef: recovers, or creates and saves, the object with the ref,
  • useMemo: recovers, or calculates and saves, the result of a callback,
  • useCallback: the same, but with the callback itself,
  • useState: provides access to directly manipulate part of the this.state
  • useReducer: like use state, …
  • useEffect: stores if it was called, and emulates componentDidMount and componentDidUnmount

But even useRef helps to keep the illusion of purity. Each time that the render function executes, we call the hooks, and they return the corresponding values. And because all impurity is under React control, although there is a lot of impurity, React can apply several of the pure functional optimizations. And we, as humans, can understand better the code because it is not split across several functions.

--

--

David Rodenas PhD
David Rodenas PhD

Written by David Rodenas PhD

Passionate software engineer & storyteller. Sharing knowledge to advance our skills. Join me on a journey of discovery in the world of software engineering.

No responses yet