React introduced hooks as a new way to manage state and side effects in functional components. Before hooks, class components were the primary way to handle state and lifecycle events in React applications.
Simplicity and Readability ๐
Reusability ๐ค
Better Performance ๐ซก
Avoiding 'this' ๐ฎโ๐จ
Aim :
we are going to create a simple counter where we used USESTATE
hook
import React, { useState } from 'react';
const [state, setState] = useState(initialState);
initialState
is the initial value of the state.state
holds the current state value.setState
is the function used to update the state. You can call it with a new value to set the state to that value, or you can pass a function that receives the previous state and returns the new state based on it.
Let's code
import React, { useState } from "react"; const Mycompnent = () => { const [count, setCount] = useState(0); const Increment = () => { // Update the count state by increasing it by 1 setCount(count + 1); }; const Decdrement = () => { // Update the count state by decreasing it by 1 setCount(count - 1); }; return ( <> <div> <h1>Counter: {count} </h1> <button onClick={Increment}>Increment</button> <button onClick={Decdrement}>Decdrement</button> </div> </> ); };
In this example:
We import React and
useState
from the 'react' package.Inside the
Mycompnent
functional component, we use theuseState
hook to create acount
state variable with an initial value of0
.We define two functions,
increment
anddecrement
, which is used to update thecount
state by increasing or decreasing it by 1.In the component's return statement, we display the current count value and two buttons. Clicking the "Increment" button calls the
increment
function, and clicking the "Decrement" button calls thedecrement
function, which updates the count and re-renders the component to reflect the new count value.
Thank you for reading my content. Be sure to follow and comment on what you want me to write about next
๐ค