useState with function
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
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:
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:
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.