![]() |
State Hooks, introduced in React 16.8, revolutionized how developers manage state in functional components. Before State Hooks, state management was primarily confined to class components using the
There are different state hooks we will learn about them: Table of Content useState Hook:useState() hook allows one to declare a state variable inside a function. It should be noted that one use of useState() can only be used to declare one state variable. It was introduced in version 16.8. Syntax:const [var, setVar] = useState(0);
Internal working of useState hook:useState() maintains state by updating a stack within the functional component’s object in memory. Each render creates a new stack cell for the state variable. The stack pointer tracks the latest value for subsequent renders. Upon user-initiated refresh, the stack is cleared, triggering a fresh allocation for the component’s rendering. Example: Below is the code example of useState Hook: Javascript
Steps to run the App: npm start
Output:
|
import React, { useReducer } from "react" ; // Defining the initial state and the reducer const initialState = 0; const reducer = (state, action) => { switch (action) { case "add" : return state + 1; case "subtract" : return state - 1; case "reset" : return 0; default : throw new Error( "Unexpected action" ); } }; const App = () => { // Initialising useReducer hook const [count, dispatch] = useReducer(reducer, initialState); return ( <div> <h2>{count}</h2> <button onClick={() => dispatch( "add" )}> add </button> <button onClick={() => dispatch( "subtract" )}> subtract </button> <button onClick={() => dispatch( "reset" )}> reset </button> </div> ); }; export default App; |
Steps to run the App:
npm start
Output:
Reffered: https://www.geeksforgeeks.org
ReactJS |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |