user10766404
user10766404

Reputation:

React hook to initial state - React native

i am currently working Hooks in react and have the following question, this simple code increments each time the button is pressed. i have create a condition that logs "finished" when the count is up to 2. However i am having trouble to put the count back to 0.

thank you very much in advance

here is my code:

import React, { useState } from 'react';

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

  if(count =='2'){
    console.log('finished')
    //count = 0
  }
  return (
    <div>
      <p>clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click here
      </button>
    </div>
  );
}

Upvotes: 0

Views: 49

Answers (1)

Anuj
Anuj

Reputation: 991

you need to use setCount method to set it back to 0

import React, { useState } from 'react';

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

  if(count === 2){
    console.log('finished')
    setCount(0);
  }
  return (
    <div>
      <p>clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click here
      </button>
    </div>
  );
}

Upvotes: 1

Related Questions