Code Skiller logoCB Logo
Logo LearnLearnLogo PracticePracticeLogo HireHireLogo IDEIDE

Using the useState hook

User image

Published by

sanya sanya

Published at: 28th Jul, 2023
1.31 mins read

The useState hook is used to add state to functional components. Prior to the introduction of hooks, state could only be managed in class components, but with hooks, we can now use state in functional components as well. The useState hook returns a state variable and a function to update that variable.

The useState takes an initial value as an argument and returns an array with the current state value and a function to update that particular state.

We can use the useState hook in a React functional component as mentioned in the points below.

  • We need to import the useState hook from React at first :

import React, { useState } from 'react';




  • Create the functional component and use the useState hook to add state:


    function Counter() {
      const [count, setCount] = useState(0);
      const handleIncrement = () => {
        setCount(count + 1);
      };
    
      return (
        <div>
          <h1>Counter: {count}</h1>
          <button onClick={handleIncrement}>Increment</button>
        </div>
      );
    }
    

In the above code, we have a simple Counter component that displays a count and a button to increment the count. The useState hook is used to create the count state variable with an initial value of 0, and the setCount function is used to update the count state when the button is clicked.

Now, when the button is clicked, the handleIncrement function is called, which in turn calls setCount, passing the updated count value. React will then re-render the component with the new count value, and we can see the updated count on the screen.

Library

WEB DEVELOPMENT

Basic

Frontend

Express JS

React

Hello World in ReactJS

Rendering Elements

States and Lifecycles in React JS

Handling Events in React JS

Introduction to JSX

Components and Props in React JS

Conditional Rendering

Lists and Keys in React JS

Introduction to Redux

Types of components (class vs functional)

Using the useEffect hook

Building custom hooks in React JS

Context API in React JS

Forms in React JS

Lifting State Up in React JS

Composition vs Inheritance

Prop drilling in React JS

Introduction to Hooks

Using the useState hook

UseMemo vs useCallback

Backend

Interview Questions

FAANG QUESTIONS