useState() – Store and Update Data
useState() is used to store data inside a React component and update it.
import { useState } from "react";
function App() {
const [count, setCount] = useState(0);
return (
<>
<h2>{count}</h2>
<button onClick={() => setCount(count + 1)}>
Click Me
</button>
</>
);
}
export default App;
useEffect() – Perform Side Effects
useEffect() is used to perform actions like fetching API data and updating the page title.
import { useEffect } from "react";
function App() {
useEffect(() => {
console.log("Welcome to React!");
}, []);
return <h2>Hello World</h2>;
}
export default App;
useRef() – Access HTML Elements
useRef() is used to access HTML elements directly and store values without causing a re-render.
import { useRef } from "react";
function App() {
const inputRef = useRef(null);
function handleClick() {
inputRef.current.focus();
}
return (
<>
<input ref={inputRef} />
<button onClick={handleClick}>
Focus Input
</button>
</>
);
}
export default App;
useNavigate() – Move Between Pages
useNavigate() is used to navigate from one page to another in React Router.
import { useNavigate } from "react-router-dom";
function Home() {
const navigate = useNavigate();
return (
<button onClick={() => navigate("/about")}>
Go to About Page
</button>
);
}
export default Home;
Top comments (0)