react-lazy-update
Optimized update hook for react.
Overview
To use state in functional components we can call useState()
hook. It returns state and state setter function.
const state setState = ;
We can call this function as many times as we need to create separate state variables.
const value1 setValue1 = ;const value2 setValue2 = ;
We can use our new values and update them using setter function:
;
After each state change our component will be re-rendered with new values. But what if we're updating state several times?
const onClick = { ; ;}; return <button onClick= onClick >update me</button>;
Fortunatelly React handles such cases - state update will be postponed (called asynchronously) and our component will be re-rendered only once. We can check it by adding some console logs:
const Button = { console; const value1 setValue1 = ; const value2 setValue2 = ; const onClick = { console; ; console; ; console; }; return <button onClick= onClick >update me</button> ;}
After click on a button we will see:
onClicksetValue1setValue2render
Nice! We updated state twice, but component re-rendered only once.
Unfortunatelly it not always works this way. Let's modify our click handler a bit:
const onClick = { console; ; };
And then click our button:
onClicktimeoutsetValue1rendersetValue2render
Oops. Now our component renders itself twice. But why? Looks like React have some problems with updating state in some uncontrolled cases (like async callbacks). There is a post about it.
But fortunatelly we can fix it with react-lazy-update
!
Installation
As any other npm package react-lazy-update
can be added to your project by following command:
npm i -S react-lazy-update
It requires any version of react
with new context API support as peer dependency, so it should be installed as well.
npm i -S react
API
lazy
react-lazy-update
exports lazy()
HoC. We just need to wrap our component with it:
; const Button = { ...} Button;
useState (useLazyState)
For lazy component we just need to replace React.useState()
with useLazyState()
provided by react-lazy-update
:
// import { useState } from 'react';;
Or we can use alias useState()
to make replacement even easier:
; const Button = { ...}; Button;
Now our button works as expected and renders only once:
onClicktimeoutsetValue1setValue2render
Nice again! =)
useReducer (useLazyReducer)
We can also replace React.useReducer()
hook with useLazyReducer()
provided by react-lazy-update
:
; const Button = { const value1 dispatch1 = ; const value2 dispatch2 = ; const onClick = { ; ; }; return <button onClick= onClick >update me</button> ;} Button;
And, of course, we can use useReducer()
alias to make life easier.