skip to Main Content

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} °
            <button style={{marginLeft: '15px'}}
                    onClick={props.increaseTemp}>
                Increase temperature by 1
            </button>
        </div>
    )
})

2

Answers


  1. I’ve never written code like this (useCallback(() => (setTemp(temp=>temp+1)),[])) while using React. I mainly use this code(useCallback(() => (setTemp(temp=>temp+1)),[])). I think this code(useCallback(() => (setTemp(temp=>temp+1)),[])) is wrong.

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search