useState Hook
The useState
hook is used to manage the state in a functional component. A basic hook allows you to declare a state variable and a function to update it.
Syntax:
const [state, setState] = useState(initialState);
Parameters:
state
: The current state value.setState
: A function that allows you to update the state.
Example: Below is the code example of useState hook.
Javascript
import React, { useState } from "react" ; import "./App.css" ; const App = () => { const [num, setNum] = useState(0); const handleClick = () => { setNum(num + 1); }; return ( <div className= "App" > <h2> {num}</h2> <button onClick={handleClick}>Add one</button> </div> ); }; export default App; |
CSS
/* Write CSS Here */ .App { display : flex; flex- direction : column; justify- content : center ; align-items: center ; } body { background-color : rgb ( 254 , 226 , 190 ); } .App>h 2 { text-align : center ; } .App>button { width : 8 rem; font-size : larger ; padding : 2 vmax auto ; height : 1.8 rem; color : white ; background-color : rgb ( 34 , 34 , 33 ); border-radius: 10px ; } button:hover { background-color : rgb ( 80 , 80 , 78 ); } |
Output:
Difference between useState and useReducer
React offers powerful tools, like `useState` for simple tasks making it a friendly companion, and `useReducer` for complex challenges, functioning like a superhero team. While both manage information, `useState` is ideal for everyday simplicity, resembling a sticky note, while `useReducer` shines in intricate scenarios, handling simultaneous complex tasks. The choice between them depends on the nature of your website’s needs and the level of complexity involved.
Table of Content
- useState Hook
- useReducer Hook
- When to use useState ?
- When to use useReducer ?
- Difference between useReducer and useState hook