Junior — Middle
Could you explain what Hooks are in the context of React or other libraries/frameworks?
sobes.tech AI
Answer from AI
Hooks are functions in React (and some other libraries) that allow you to use state and other React features without writing classes. They enable you to "hook into" the component lifecycle and manage state in functional components.
Main hooks:
- useState — for storing and updating state.
- useEffect — for performing side effects (e.g., data loading, subscriptions).
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]);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Thus, Hooks make component code more concise and convenient for reusing logic.