React JS 19 Tutorial in Hindi #53 - Custom Hooks in Reactjs

What are custom Hook

Make custom hook for toggle UI

Interview Question

A Custom Hook is just a JavaScript function that starts with the word use and allows you to reuse stateful logic between components.

Instead of writing the same logic in multiple components, you can extract it into a custom hook and use it wherever needed.


export default function App() {

function Child(){
return <h1>Child Component</h1>
}
return (
<div>
<h1>Parent component</h1>
<Child />
</div>
)

}


import { useState } from "react";

const useToggle=(defaultVal)=>{
const [value,setValue]=useState(defaultVal);

function toggleValue(val){

console.log(val);
if(typeof val!='boolean'){
console.log("if");
setValue(!value)
}else{
console.log("else");
setValue(val)
}
}
return [value,toggleValue];
}

export default useToggle;