Skip to content
the poor coder

useState with function

Poor Man
Published
Reading time
1 min read
On this page

Using useState Hook with Function Component#

When it comes to managing state in a function component, the useState hook provides a convenient way to do so. With useState, you can define a state variable and a function to update it. Whenever the state is updated, the component will re-render, reflecting the new state.

Syntax#

JavaScript

    const [stateVar, setState] = useState(initialState);
  • stateVar: the state variable that holds the current value of the state.
  • setState: the function to update the state variable.
  • initialState: the initial value of the state variable.

Example#

Let's take an example of a counter:

JavaScript

    import React, { useState } from 'react';

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

        return (
            
                Count: {count}
                 setCount(count + 1)}>Increment
                 setCount(count - 1)}>Decrement
            
        );
    }

In this example, we start with an initial state of zero. The setCount function is used to update the state variable count. We pass the new value of count as an argument to the function. When we click on either of the buttons, the count value will be updated, and the component will re-render.

We can also use the useState hook to manage more complex state objects or arrays. For example:

JavaScript

    const [stateObj, setStateObj] = useState({ name: "", age: 0 });

    const [list, setList] = useState([]);

By using the useState hook, we can easily manage state in function components, making them more reusable and easier to reason about.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC