(ReactJS) Understand the nature of Hook in React

Thoai Huynh
4 min readAug 14, 2019

Hooks are added to React 16.8 at React conference 2018. Newly added features are great for Stateful Componentsor Stateless Components and it can do everything as same as the Stateful Components.Another day, I will have an article analyzing the meaning of these components.

Back to this article, some people will ask themselves questions about why should we use Hook? When we use React Hooks, there will be the following benefits:

  1. Make components become more compact.
  2. Allows us to use state within the functional component.
  3. The bundle size will be greatly reduced by using Hooks. (Because Class inherits from React Component)

Now, I will briefly summarize how to use some of React Hook’s main functions: useState, useEffect, useRef, useMemo, useCallback.

useState

useState() is the function that you will use a lot. Instead of using this.state from the Stateful Components, you can access the current state with a initial value and can change this state by function.

How to use useState()

useEffect

useEffectrelated to side effects and it allows us to make changes to the functional component. Hook has the same effect as ComponentDidMount, ComponentDidUpdate, and ComponentWillUnMount, but is grouped into a single function. useEffect is used to optimize function call and clean up. And it has 2 parameters:

  1. A anonymous function has no parameters.
  2. An array contains parameters, the above function is only called when this parameter changes.
Fetch data by useEffect

For ComponentDidUpdate, it will depend on the second parameter in useEffect. Conversely, if it is an empty array, it will only run once as same as ComponentDidMount

In addition, no ComponentWillUnMountfunction for functional component. How to clean up?

Clean up functional component

counter unmounted will appear when you navigate to other page.

useContext

As you know, Redux has a store that stores the entire state of the app. However it is relatively heavy and affects the ability to load bundle files on production environment. Therefore, ReactJS just released useContext to replace Redux.

UseContext

UseMemo

As you know, there are many ways to optimize performance for React applications. You can use shouldComponentUpdate, PureComponent or memo,… that helps your app avoid re-render. However, today I will introduce to you about useMemo

useMemo is a function -> takes a function and an array of dependencies. The input function for useMemo must return a value, and when one of the dependencies changes, useMemo will execute the passed function again.

For Example:

useEffect + useState
useMemo

Lets suppose numberProp is initially 0:

  • The useMemo version immediately renders 1.
  • The useEffect version renders null, then after the component renders the effect runs, changes the state, and queues up a new render with 1.

useCallback

useCallback is similar to useMemo. But it returns thefunction callback, not a value. This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.

useCallback(fn, deps) is equivalent to useMemo(() => fn, deps).

So when should I useMemo and useCallback?

Firstly, I will have a example below:

Make sure you think that it will re-render after name or age updated. However, you have encountered a real trick.

Explain: Thanks to comparison operators check on options between every render andoptions will be new every time => it'll always evaluate to true, meaning the useEffectcallback will be called after every render rather than only when name and agechange.

Solution:

Oh, it’s really effective in this case. However, if we think more deeply, name or age is not string, number,… but a function, object, array type. Mean that, name or age will always be evaluate as change :))))

Therefore, useMemo or useCallbackis generated to solve this situation.

useRef

Now you can use useRef to replace this.myRef = React.createRef () in the component class. useRef is used to access elements inside HTML Node. useRefreturns a ref object and will be kept throughout the life of the component.

Use ESLint Plugin to check for errors

Eslint react hook

In Conlusion

I think Hook is very good but we have to know how to apply it properly. Besides, there are also some less common Hook like: useReducer, useImperativeHandle, useLayoutEffect, useDebugValue.

And here is a custom hook library that I really like. You can research it through: https://github.com/streamich/react-use

Reference source: https://reactjs.org/docs/hooks-intro.html

--

--