Implement an optimized version of the useCounter hook. The returned methods should be memoized, the same function instance is returned across re-renders.
export default function Component() {const { count, increment, decrement, reset, setCount } = useCounter();return (<div><p>Counter: {count}</p><button onClick={increment}>Increment</button><button onClick={decrement}>Decrement</button><button onClick={reset}>Reset</button></div>);}
initialValue: number: Initial value of the counter state. If not provided, it should default to 0.The useCounter hook returns an object with the following properties:
count: number: The current counter valueincrement: () => void: A function to increment the counter valuedecrement: () => void: A function to decrement the counter valuereset: () => void: A function to reset the counter value to initialValue, or 0 if not providedsetCount: (value: number) => void: A function to set the counter value to value, it has the same signature as setStateincrement, decrement, reset, and setCount must be the same function instance across re-renders.
This follow-up keeps the same counter behavior as useCounter, but adds a stronger API guarantee: the returned helper methods should keep the same function identity across re-renders.
The hook still returns the current count, the raw setCount setter, and three convenience helpers. The implementation has two responsibilities:
count in useStateuseCallbackincrement and decrement use updater functions, so they never depend on a captured count value and stay correct across queued updates. reset is the only helper that depends on initialValue, because its job is to restore that original starting point.
setCount itself is already stable because React guarantees that a useState setter does not change identity between renders.
import { useCallback, useState } from 'react';/*** @param number initialValue* @return Object*/export default function useCounter(initialValue = 0) {const [count, setCount] = useState(initialValue);const increment = useCallback(() => {setCount((x) => x + 1);}, []);const decrement = useCallback(() => {setCount((x) => x - 1);}, []);const reset = useCallback(() => {setCount(initialValue);}, [initialValue]);return {count,increment,decrement,reset,setCount,};}
reset legitimately changes identity when initialValue changes, because the value it restores has changed.setCount keeps React's full Dispatch<SetStateAction<number>> type so callers can pass either a number or an updater function.console.log() statements will appear here.