この解答例はChatGPTによって生成されています,正しいかは自己判断で。

BFE.devでのAI解答例 - React コーディング問題
5. usePrevious()

import { useEffect, useRef } from 'react';

const usePrevious = (value) => {
  const ref = useRef();
  
  useEffect(() => {
    ref.current = value;
  });

  return ref.current;
};

export default usePrevious;

Usage:

import usePrevious from './usePrevious';

const MyComponent = () => {
  const [count, setCount] = useState(0);
  const prevCount = usePrevious(count);

  return (
    <div>
      <p>Current count: {count}</p>
      <p>Previous count: {prevCount}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};