Search code examples
reactjsreact-hooksrerender

useCallback + setState. Using previous state value vs passing the state as a dependency


So the task is:

  1. When you click on the "Increase temperature by 1 degree" button, the temperature increased

  2. The TempDisplay component should not be rerendered when clicking on the "Increase by 10 seconds" button

My solutions:

useCallback(() => (setTemp(temp+1)),[temp])

and

useCallback(() => (setTemp(temp=>temp+1)),[])

Is any of this solutions wrong and what's the difference? Or both can be used?

Full code:

export const App = () => {
    const [temp, setTemp] = useState(10)
    const [seconds, setSeconds] = useState(100)

    const increaseSeconds = () => setSeconds(seconds + 10)

    const increaseTemp = XXX here we need to define the function XXX

    return <>
        <TempDisplay temp={temp} increaseTemp={increaseTemp}/>

        <div>
            <b>Seconds :</b> {seconds} с
            <button style={{marginLeft: '15px'}}
                    onClick={increaseSeconds}>
                Increase by 10
            </button>
        </div>
    </>
}
const TempDisplay = React.memo((props: any) => {
    console.log('Render TempDisplay')
    return (
        <div style={{marginBottom: '15px'}}
             onClick={props.reset}>
            <b>Temperature:</b> {props.temp} &#176;
            <button style={{marginLeft: '15px'}}
                    onClick={props.increaseTemp}>
                Increase temperature by 1
            </button>
        </div>
    )
})

Solution

  • If you passed the [] as a callback dependency, the callback function will not get recreated even if the dependency value gets updated.

    Hence, you will not get updated values for temp at the time callback function get called