- React Hooks are functions that allow you to hook into React state and lifecycle features from functional components.
useState()
-It returns variable & function
-It triggers rerendering
import { useState } from "react";
function Count() {
const [count, setCount] = useState(10);
function increase() {
setCount(count + 1);
}
function decrease() {
setCount(count - 1);
}
function reset() {
setCount(0);
}
return (
<div>
<h1>Counter App</h1>
<h3>Count: {count}</h3>
<button onClick={increase}>+</button>
<button onClick={decrease}>-</button>
<button onClick={reset}>Reset</button>
</div>
);
}
export default Count;
useEffect
useEffect is a React Hook that lets you synchronize a component with an external system.
The useEffect Hook takes two arguments: a function containing your side effect code and an optional dependency array .
import { useEffect } from "react";
function App() {
useEffect(() => {
console.log("Component Mounted");
}, []);
return (
<div>
<h1>Hello React</h1>
</div>
);
}
export default App;
useNavigate
- useNavigate is a hook in React Router used to move from one page to another programmatically.
import { useNavigate } from "react-router-dom";
function Home() {
const navigate = useNavigate();
function goToAbout() {
navigate("/about");
}
return (
<div>
<h1>Home Page</h1>
<button onClick={goToAbout}>
Go to About
</button>
</div>
);
}
export default Home;
Top comments (0)