react hooks previous state code example
Example 1: useRef
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
Example 2: useeffect previous state
const Component = (props) => {
const {receiveAmount, sendAmount } = props
const usePrevious = (value) => {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
const prevAmount = usePrevious({receiveAmount, sendAmount});
useEffect(() => {
if(prevAmount.receiveAmount !== receiveAmount) {
}
if(prevAmount.sendAmount !== sendAmount) {
}
}, [receiveAmount, sendAmount])
}
Example 3: usestate access previous state
const [arrayOfObjs, handleObjSelection] = useState([]);
<button
onClick={selectedObj => handleObjSelection(
prevSelected => [...prevSelected, selectedObj],
))}
>