import { useEffect, useRef } from 'react';

/**
 * A convenience hook that will return the value of the input
 * from the previous render. You could consider this the class
 * component equivalent of `prevProps` from the life cycle
 * method: `componentDidUpdate`.
 *
 * Example:
 *
 * function myComponent(isVisible) {
 *  const [state, setState] = useState(initialState);
 *  const wasPreviouslyVisible = usePrevious(isVisible);
 *
 *  useEffect(() => {
 *    if (isVisible && !wasPreviouslyVisible) {
 *      setState(initialState);
 *    }
 *  }, [isVisible]);
 * }
 */

export default function usePrevious(value, initialValue = null) {
  const ref = useRef(initialValue);
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
}