JavaScriptReact

Using the State Hook

The React useState Hook allows us to track state in a function component. State generally refers to data or properties that need to be tracking in an application.

To use the useState Hook, we first need to import it into our component.

import React, { useState } from 'react';

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

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

export default Counting;

How to Increment and Decrement Number Using React Hooks

I have created increment or decrement functionality with the group of increment button {plus (+) button}, decrement button {minus (-) button } and a text input field.  So that –

  • When you click the plus button, It will increase the input value  by 1
  • When you click the minus button, It will decrease the input value by 1
  • You can click both buttons multiple times to increase or decrease the input value multiple times by 1.
  • You can also, enter a number into the input field, you can also increase or decrease that number by clicking the plus or minus button.
import React, { useState } from 'react';

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

   const plusCounter = () => {
     setCount(count+1);
   }

    const minusCounter = () => {
    if(count > 0){ 
    setCount(count-1);
    }
   }

  return (
    <>
      <p>You clicked {count} times</p>
      <button onClick={plusCounter}>
        +
      </button>

      <button onClick={minusCounter}>
        -
      </button>
   
    </>
  );
}

export default Counting;

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button