React JS 19 Tutorial in Hindi #51 Rules for React js Hooks

Rules for Hooks

Example

Interview Question

Start with use_____

useState

useEffect

useRef

export default function App() {
const [user,setUser] = useState(); //correct
if (condition) {
const [data,setData] = useState(); // not correct
}
return (
<div>
<h1>Hook Rules in React js</h1>
</div>

)

}



🔴 Do not call Hooks inside conditions or loops.
🔴 Do not call Hooks after a conditional return statement.
🔴 Do not call Hooks in event handlers.
🔴 Do not call Hooks in class components.
🔴 Do not call Hooks inside try/catch/finally blocks.


Don’t call Hooks from regular JavaScript functions.
Instead, you can:
✅ Call Hooks from React function components.
✅ Call Hooks from custom Hooks.


function FriendList() {
const [onlineStatus, setOnlineStatus] = useOnlineStatus(); //
}
function setOnlineStatus() { //Not a component or custom Hook!
}
const [onlineStatus, setOnlineStatus] = useOnlineStatus();


=
Note
Custom Hooks may call other Hooks (that's their whole purpose). This works because custom Hooks are also supposed to only be called while a function component is rendering.