1

The given custom hook has a variable count and a setCount function and it return count and another function that under the hood uses setCount to change the count variable.

I am curious to know how this works. Is it because the function useCounter creates a closure?

import {useState} from "react"

function useCounter() {
    const [count, setCount] = useState(0)

    function increment() {
        setCount(prevCount => prevCount + 1)
    }

    return [count, increment]
}

export default useCounter
Khiladi420
  • 21
  • 3
  • React will keep track of the state for you through all renders of all components using the hook using it's internal mechanisms for doing so. Explaining how that works is beyond the scope of an SO answer (no, it's not because of lexical closure). TL;DR it's some React voodoo magic, it's complicated. – Jared Smith May 21 '20 at 02:24
  • Read the source code, starting with the hooks code: https://github.com/facebook/react/blob/master/packages/react/src/ReactHooks.js – Drew Reese May 21 '20 at 04:44

0 Answers0