0

I was reading up on React hooks when i stumbled up on this code.

import React, { useState, useEffect } from 'react';

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

  // Similar to componentDidMount and componentDidUpdate
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

I'm trying to understand how this declaration const [count, setCount] = useState(0); was later used in this manner setCount(count + 1).

Devops-Paddy
  • 97
  • 1
  • 9
  • What exactly isn't clear to you? Do you understand how `count` gets a value? Do you understand how `setCount` triggers the component to be refreshed (the function gets executed again) ? – Jonas Wilms May 02 '19 at 15:25
  • `const [count, setCount] = useState(0);` and why it could later on be used like this `setCount(count + 1)` – Devops-Paddy May 02 '19 at 15:27
  • 6
    It looks like you're reading the docs from the [react hooks guide](https://reactjs.org/docs/hooks-state.html) in which they explain [array destructuring on the same page just further down](https://reactjs.org/docs/hooks-state.html#tip-what-do-square-brackets-mean). – chazsolo May 02 '19 at 15:27
  • 2
    Maybe, giving a read to [destructuring assigment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) can give you some light – Shidersz May 02 '19 at 15:28
  • The question as is is too broad to be answered. Please read through all the links we provided to you, if there is still something unclear ask a new question stating what exactly you think happens, and what exactly you did not understand. We will be glad to help :) – Jonas Wilms May 02 '19 at 15:33
  • Oh okay, thanks everyone. And thank you @Shidersz. I finally understand this method and what it's called in javascript – Devops-Paddy May 02 '19 at 15:33
  • @JonasWilms i don't think this question is a duplicate. I believe he needed know about array destructuring – Ikechukwu May 03 '19 at 08:04

0 Answers0