React Hooks in Practice (Tricks and Best Practices)

Everton Menezes
The Startup
Published in
3 min readNov 12, 2020

My object here isn’t explain how each hook works, my object is explain how use hook to get best performance and some tricks that I learned with life. I ever search how is the right way to use the hooks and it is very hard to find the answers so I decided share this knowledge.

All React codes are functions, their has life cycle, when the component render all variables (except hooks) are recreate so if you need to keep a value you need to use “useState” for it, look next code:

useState

We use “useState” to keep variable while the component is alive

The above code there are multiples state and anyone other hook, whats is happening when an input change his value? All input will be render but do we need render the list of results when we change an input? NO! For it we have the hook “useMemo”, let’s apply it, see the next code:

useMemo

We use “useMemo” to put a variable in memory, we can put a component in memory so this component will be to render when his dependences change

Now, each part of code will be render once time, you can see that with “console.log”, but the function “_divResult” is rendering twice time, when the “result” and “listResult” change but we have a solution for that, “useState”, see below:

useState

We use “setState” for change the state value

We can pass an arrow function to “setState”(setListResult), the parameter of this function is the old value so we don’t need to pass the variable “listResult” as parameter of “_divResult” because we can use “oldValue”.

useState (trick)

Curiosity: We can use a complete logic in this “setState”.

Now I need to talk about “useCallback”, see below:

I put the function “_calculate” as dependence of “_divCalculate”, the function “_calculate” isn’t in memory so it is rendering always and “_divCalculate” too.

Remember, console is your best friend

“useCallback is similar to “useMemo” but is used to save function

Now, the function “_calculate” it is in memory, this function will be render only when their dependence changes.

Finally, we’re arriving on “memo”, look that:

memo is similar to “useMemo” but is used to save file

The code above there is the same result but we can put the right code in a new file, with “memo” the component will be render only when the props change.

Is it today, comment your opinion and if it helps you, see you later.

Project link: https://github.com/evertonsmenezes/ReactHooksInPratice

--

--