Hooks In React
what are Hooks
In React, a hook is a special function that allows functional components to use state and other React features without needing to write a class. Hooks are JavaScript functions that "hook into" React state and lifecycle features. They enable you to manage state, perform side effects, and access context in functional components.
What problem hook solve
Before hooks, React components were like fancy boxes with lots of hidden buttons inside (like state and lifecycle methods). Classes could access these buttons, but functional components couldn't. Hooks essentially add these buttons to functional components, so now they can use things like state, effects, and context just like classes could. It's like upgrading functional components to have all the abilities of class components, but in a simpler and more flexible way!
useState
useState
is a React hook that allows functional components to manage state. It is one of the most fundamental and commonly used hooks in React. Here's how you can use useState
in React:
import React, { useState } from 'react';
function Counter() {
// Declare a state variable named "count" with an initial value of 0
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
{/* When the button is clicked, update the "count" state */}
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
In this example:
useState(0)
initializes thecount
state variable with a value of 0.count
holds the current state value, andsetCount
is a function that allows you to update thecount
state.When the button is clicked, the
setCount
function updates thecount
state, causing the component to re-render with the new state value.
useCallback
useCallback
is a React hook that returns a memoized version of the callback function that only changes if one of the dependencies has changed. It is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary re-renders.
const passwordGenerator=useCallback(()=>{
let pass="";
let str="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
if(numberAllowed) str+="123456789";
if(charAllowed)str+="!`~@#$%^&*(){}[]";
for(let i=1;i<Length;i++) {
let char=Math.floor(Math.random()*str.length+1)
pass+=str.charAt(char)
}
setpassword(pass);
},[Length,numberAllowed,charAllowed]);
In this example, the useEffect
hook runs whenever the passwordGenerator
function changes (due to changes in Length
, numberAllowed
, or charAllowed
). It calls the passwordGenerator
function, generating a new password and updating the password
state. This pattern ensures that the password is generated and updated whenever the relevant dependencies change.
useEffect
In React, the useEffect
hook allows you to perform side effects in functional components. Side effects are operations that affect the outside world, such as data fetching, subscriptions, or manually changing the DOM. useEffect
is similar to componentDidMount
, componentDidUpdate
, and componentWillUnmount
combined in class components.
import React, { useEffect, useState } from 'react';
function PasswordComponent() {
const [password, setpassword] = useState('');
const passwordGenerator = () => {
let pass = "";
let str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
if (numberAllowed) str += "123456789";
if (charAllowed) str += "!`~@#$%^&*(){}[]";
for (let i = 1; i < Length; i++) {
let char = Math.floor(Math.random() * str.length);
pass += str.charAt(char);
}
setpassword(pass);
};
useEffect(() => {
passwordGenerator(); // Call passwordGenerator function when Length, charAllowed, or numberAllowed change
}, [Length, charAllowed, numberAllowed]);
return (
<div>
<p>Password: {password}</p>
{/* Other JSX content */}
</div>
);
}
In this code:
useEffect
is used to invoke thepasswordGenerator
function whenever any of its dependencies (Length
,charAllowed
, ornumberAllowed
) change. When these dependencies change, theuseEffect
hook triggers the execution ofpasswordGenerator
.passwordGenerator
generates a password based on the values ofLength
,charAllowed
, andnumberAllowed
, and then updates thepassword
state usingsetpassword(pass)
.The effect runs after the initial render and whenever any of the specified dependencies change. When these dependencies change, the effect re-runs, and the
passwordGenerator
function is called again to generate a new password based on the updated criteria.