Skip to content

Commit

Permalink
perf(usebarcodefinder.ts): change 4 usestates to usereducer
Browse files Browse the repository at this point in the history
  • Loading branch information
nartc committed Mar 3, 2020
1 parent c066748 commit af7e608
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 16 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@
"@commitlint/config-conventional": "8.3.4",
"@types/jest": "25.1.3",
"@types/react": "16.9.23",
"@types/react-native": "0.61.17", "commitizen": "4.0.3",
"@types/react-native": "0.61.17",
"commitizen": "4.0.3",
"cz-conventional-changelog": "3.1.0",
"husky": "4.2.3",
"lint-staged": "10.0.8",
Expand Down
49 changes: 34 additions & 15 deletions src/hooks/useBarcodeFinder.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { CustomBarcodeRead } from 'interfaces';
import { useCallback, useState } from 'react';
import { Reducer, useCallback, useReducer, useState } from 'react';
import { LayoutChangeEvent } from 'react-native';
import { BoundingRect, CustomBarcodeRead } from '../interfaces';

/**
* @internal
Expand All @@ -14,23 +14,42 @@ export default (
customBarcodeRead?: CustomBarcodeRead | number
) => {
const [barcodeRead, setBarcodeRead] = useState(false);
const [finderWidth, setFinderWidth] = useState(0);
const [finderHeight, setFinderHeight] = useState(0);
const [finderX, setFinderX] = useState(0);
const [finderY, setFinderY] = useState(0);
const [state, dispatch] = useReducer<
Reducer<
BoundingRect,
{
type: 'SET';
payload: BoundingRect;
}
>
>(
(prev, action) => {
switch (action.type) {
case 'SET': {
return { ...prev, ...action.payload };
}
default: {
return prev;
}
}
},
{
width: 0,
height: 0,
x: 0,
y: 0,
}
);
const _onBarcodeFinderLayoutChange = useCallback(
(event: LayoutChangeEvent) => {
const {
nativeEvent: {
layout: { height, width, x, y },
},
} = event;
setFinderWidth(width);
setFinderHeight(height);
setFinderX(x);
setFinderY(y);
dispatch({ type: 'SET', payload: { height, width, x, y } });
},
[finderX, finderY, finderHeight, finderWidth]
[state.height, state.width, state.x, state.y]
);

let timeoutId = 0;
Expand Down Expand Up @@ -61,10 +80,10 @@ export default (
customBarcodeRead && typeof customBarcodeRead === 'object'
? null
: barcodeRead,
finderX,
finderY,
finderWidth,
finderHeight,
finderX: state.x,
finderY: state.y,
finderWidth: state.width,
finderHeight: state.height,
onBarcodeFinderLayoutChange: _onBarcodeFinderLayoutChange,
processingReadBarcode,
};
Expand Down

0 comments on commit af7e608

Please sign in to comment.