React Hook: useState simplified

React Hook: useState simplified

·

2 min read

Intro to React hooks

React hooks are just JavaScript functions by React. and it starts with the use keyword. Hooks are only used in function components and we have to use them inside the function component.

Always use hooks at the top level of your component and don't use inside loops, conditions, and nested functions. Using this rule we can ensure that hooks are called in the same order each time component renders.

useState Hook

React useState hook is the most popular and commonly used hook. useState helps to manage state in our function component.

useState returns two values state and a function to update the state. and we can pass to useState a parameter it will be an initial value of the state.

const [state, setState] = React.useState(initalValue)

What is State?

A State in react is info or value that changes throughout the app's lifecycle. That's why states are mutable. and we can modify the state in react using useState which provides a function to update the state.

How to use

  1. We have to import useState in our component
import { useState } from 'react'

2. Now we can use useState and there are two ways we can use it by using array indexing and array destructuring

a. Array indexing

const countArray = useState()
const count = countArray[0] // The State
const setCount = countArray[1] // The Update Function

b. Array Destructuring

const [count , setCount] = useState(initialValue)

count: the current state (value).

setCount: it's a function that will update the count state. we can name anything but the preferred way to use the set in front of our state name.

useState(initialValue): its react hook and it accepts a value. value is not compulsory we can provide the initial value for our state.

useState Example

import React, { useState } from "react";

const App = () => {
  const [count, setCount] = useState(0);
  return (
    <div>
      <h1>Count value</h1>
      <p>{count}</p>
      <button onClick={() => setCount(count + 1)}>Increase</button>
    </div>
  );
};
export default App;

Open CodeSandBox

Example explanation

  1. Import useState from React.

  2. Initialize useState using array destructuring.

  3. The count is the state and setCount is a function that modifies the count variable.

  4. In the p element, we display the count value.

  5. Using the button we increase the count value using the onClick event and using setCount we can increase the count value.

Reference from

  1. Learn useState In 15 Minutes - React Hooks Explained by Web Dev Simplified
  2. Guide useState by blog.logrocket
  3. Codevolution: React Hooks

Thank You