react hooks previous state code example

Example 1: useRef

/*
	A common use case is to access a child imperatively: 
*/

function TextInputWithFocusButton() {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    // `current` points to the mounted text input element
    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

// declare usePrevious hook
    const usePrevious = (value) => {
      const ref = useRef();
      useEffect(() => {
        ref.current = value;
      });
      return ref.current;
    }    
    
// call usePrevious hook on component state variables to store previousState
    const prevAmount = usePrevious({receiveAmount, sendAmount});
  
  	// useEffect hook to detect change of state variables
    useEffect(() => {
        if(prevAmount.receiveAmount !== receiveAmount) {

         // process here
        }
        if(prevAmount.sendAmount !== sendAmount) {

         // process here
        }
    }, [receiveAmount, sendAmount])
}

Example 3: usestate access previous state

const [arrayOfObjs, handleObjSelection] = useState([]);

// on a buttton for example
<button
  onClick={selectedObj => handleObjSelection(
              prevSelected => [...prevSelected, selectedObj],
  		  ))}
>