sancodes
sancodes

Reputation: 1662

conceptual understanding of square bracket destructuring in react

import React, { useEffect, useState } from 'react'
import { Text } from 'react-native'

export default function Counter() {
  const [count, setCount] = useState(0)

  useEffect(() => {
    const id = setInterval(() => setCount((count) => count + 1), 1000)

    return () => clearInterval(id)
  }, [])

  return <Text style={{ fontSize: 120 }}>{count}</Text>
}

so how does the count and setCount get values from useState(0)

const [count, setCount] = useState(0)

can you walk me through this confusion, as if I'm five.

Upvotes: 2

Views: 991

Answers (3)

Alok Singh
Alok Singh

Reputation: 181

After every 1000 ms (1 sec)

useEffect(() => {
    const id = setInterval(() => setCount((count) => count + 1), 1000)

    return () => clearInterval(id)
  }, [])

this function called and update the value of count.

setInterval function sets the time interval when it called again automatically

I hope you will clear about that.

Upvotes: -1

DaanKode
DaanKode

Reputation: 131

The useState hook simply returns an array with two values: the first one is the value that you will want to use in your component, and the second one is the function that you can invoke to change the value. The useState hook takes an argument that allows you to set the initial value.

For further reading, please refer to the React documentation: https://reactjs.org/docs/hooks-state.html

The bracket notation simply destructures the array that the useState hook returns, so that you can easily access its values in your component.

Upvotes: 3

m90
m90

Reputation: 11822

The function useState returns an array wrapping two values (the stateful value and the setter). This is done so that a single function call can return two values at once (which is not supported by JavaScript as a language - other languages do support such things though).

Example:

function neighbors (num) {
  return [num - 1, num + 1]
}

const [seven, nine] = neighbors(8)

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#array_destructuring

Upvotes: 2

Related Questions