useState hook in React Js
- Get link
- X
- Other Apps
useState hook in React Js
In React, useState
is a built-in hook that allows functional components to have stateful behavior. It is used to declare state variables and update them as necessary. The useState
hook returns an array of two values: the current state and a function to update the state.
Here is the basic syntax of useState
:
import React, { useState } from 'react'; function Example() { const [state, setState] = useState(initialState); // ... }
The first element of the returned array, state
, is the current state of the component. The second element, setState
, is a function that allows you to update the state. You can call this function with a new value to update the state.
The useState
hook takes one argument, which is the initial state of the component. This argument can be any value, including objects and arrays. When the component is first rendered, the useState
hook initializes the state to this value.
Here is an example of how to use useState
to declare a counter state variable and update it:
import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); function increment() { setCount(count + 1); } return ( <div> <p>You clicked {count} times</p> <button onClick={increment}>Click me</button> </div> ); }
In this example, the useState
hook is used to declare a count
state variable and initialize it to 0
. The increment
function uses the setCount
function to update the state by incrementing the current value of count
. The count
state variable is then used in the JSX to display the current count value.
It's important to note that when you update state using useState
, React will re-render the component with the updated state. This means that any changes to the state will cause the component to re-render, updating the user interface to reflect the new state.
Happy Learning!! Happy Coding!!
- Get link
- X
- Other Apps
Comments