Middle
Tell us about React hooks and the rules for using them.
sobes.tech AI
Answer from AI
React hooks are functions that allow you to use state and other React features in functional components.
Main hooks:
- useState — for managing state.
- useEffect — for side effects (loading data, subscriptions).
- useContext — for accessing context.
Rules for using hooks:
- Call hooks only at the top level of a component, not inside loops, conditions, or nested functions.
- Call hooks only from React functional components or custom hooks.
Example of using useState and useEffect:
import React, { useState, useEffect } from 'react';
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]); // effect runs when count changes
return (
<button onClick={() => setCount(count + 1)}>
Click me
</button>
);
}