-1
import React from "react"
import ReactDOM from "react-dom"
import "./styles.css"

function usePersistentValue(initialValue) {
  return React.useState({
    current: initialValue
  })[0]
}

function Counter() {
  const [count, setCount] = React.useState(0)
  const id = usePersistentValue(null)

  const clearInterval = () => window.clearInterval(id.current)

  React.useEffect(() => {
    id.current = window.setInterval(() => {
      setCount(c => c + 1)
    }, 1000)

    return clearInterval
  }, [])

  return (
    <div>
      <h1>{count}</h1>
      <button onClick={clearInterval}>Stop</button>
    </div>
  )
}

const rootElement = document.getElementById("root")
ReactDOM.render(<Counter />, rootElement)

here

function usePersistentValue(initialValue) {
      return React.useState({
        current: initialValue
      })[0]
    }
 

it seems a function call but followed by [0] makes no sense for me, especially what [0] doing here? is it valid javascript or a special syntax for react? my best guess here the [0] value gets assigned to current property ,am i right? but im still confused how array value get assigned to the current property, please help me explaining the syntax thank you

ask455
  • 23
  • 6
  • Perfectly valid, regular JS syntax. Your function returns the `0` property of whatever `React.useState()` returns. – Lennholm Nov 10 '20 at 15:23
  • `useState` data shouldn't be mutated. It looks like you'd need `useRef` instead. See [how to use it to manage a timer id](https://stackoverflow.com/q/53090432/1218980). – Emile Bergeron Nov 10 '20 at 15:57

3 Answers3

2

[0] just gets the 0 property from something, typically an array.

function return_an_array() {
    return ["foo", "bar"];
}

const result = return_an_array()[0];

console.log(result);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

This is exactly the same as:

const [id] = useState({ current: null });

useState returns an array of two values, the constant state value that you use and do not change and a "set" function that you use to change the state. You can see a "normal" example of that in the line const [count, setCount] = React.useState(0)

The weird thing in this code is that they are working around the rules by changing the contents of id later without actually calling a function to set the updated state. Instead, they sweep it under the rug by hiding in a function.

crashmstr
  • 28,043
  • 9
  • 61
  • 79
0

think of it like this

return ( React.useState({ current: initialValue })[0] )

(parenthesis for emphasis)

So it first evaluates React.useState({ current: initialValue })[0] - which will result in something - that is what is being returned. the [0] is on the return value of .useState not the return statement.

Chase
  • 5,315
  • 2
  • 15
  • 41