React Hooks
React Hooks are functions that allow you to use state and other React features in functional components. Introduced in React 16.8, they eliminate the need for class components and make function components more powerful.
1 useState Hook
The useState hook lets you add state to functional components. It returns an array with two elements: the current state and a function to update it.
App.js
</>
Copy
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // Initialize state
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default Counter;
Explanation:
useState(0): Initializes the state with a value of0.- The value returned by
useState()is stored in[count, setCount]. Therefore,countholds the current state, andsetCountis the function to update it. - We are calling the
setCountfunction to update thecounttocount+1, when the button is clicked. We pass the new valuecount+1as argument to thesetCountfunction. - The component re-renders whenever the state changes.
Output Video:
2 useEffect Hook
The useEffect hook allows you to perform side effects in functional components, such as data fetching, subscriptions, or directly updating the DOM.
App.js
</>
Copy
import React, { useState, useEffect } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(seconds => seconds + 1);
}, 1000);
return () => clearInterval(interval); // Cleanup on unmount
}, []); // Empty array ensures it runs only once
return <h2>Elapsed Time: {seconds} seconds</h2>;
}
export default Timer;
Explanation:
- The
useEffecthook sets up a timer usingsetInterval. - The cleanup function ensures the timer is cleared when the component unmounts.
- An empty dependency array (
[]) ensures the effect runs only once.
Output Video:
3 useContext Hook
The useContext hook provides an easy way to consume context values without needing to wrap components in a Consumer.
App.js
</>
Copy
import React, { createContext, useContext } from 'react';
const UserContext = createContext();
function UserProfile() {
const user = useContext(UserContext);
return <h2>User: {user}</h2>;
}
function App() {
return (
<UserContext.Provider value="Alice">
<UserProfile />
</UserContext.Provider>
);
}
export default App;
Explanation:
createContext: Creates a context for the user.useContext: Consumes the context value without needing a wrapper component.- In this example, the
UserProfilecomponent dynamically displays the user’s name.
Output:
