Refactor a React Class Component with useContext and useState Hooks

InstructorKent C. Dodds

Share this video with your friends

Send Tweet

We've got a pretty simple User class component that manages a bit of state and uses some context. Let's refactor this over to a function component that uses the useContext and useState hooks.

shyam
shyam
~ 2 years ago

why did we not use something like onUpdate={() => setFilter(filter)}

shyam
shyam
~ 2 years ago

why did we not use something like onUpdate={() => setFilter(filter)}

Kent C. Dodds
Kent C. Dodds(instructor)
~ 2 years ago

Where would filter come from in that case? Go ahead and try it and see what happens 😀

Alex Krasnicki
Alex Krasnicki
~ 2 years ago

While looking at the example code on github I've noticed that on this lesson's branch something was added to the Query component. Namely:

function useDeepCompareEffect(callback, inputs) {
  const cleanupRef = useRef()
  useEffect(() => {
    if (!isEqual(previousInputs, inputs)) {
      cleanupRef.current = callback()
    }
    return cleanupRef.current
  })
  const previousInputs = usePrevious(inputs)
}

I'm curious why you need to do it this way? Would't just running callback if the condition is met fit the bill? Why the cleanupRef?

Nash Kabbara
Nash Kabbara
~ a year ago

Thanks for the course Kent. I came to this lesson to make the same comment as Alex. Wouldn't something like below do the same?

function useDeepCompareEffect(callback, inputs) {
  let cleanup
  useEffect(() => {
    if (!isEqual(previousInputs, inputs)) {
      cleanup = callback()
    }
    return cleanup
  })
  const previousInputs = usePrevious(inputs)
}