React Hooks are functions that let developers use state and other React features in functional components. They were introduced in React 16.8 to allow side effects in functional components, which were initially stateless and did not handle lifecycle methods. The most commonly used hooks are `useState` and `useEffect`, but there are several others as well.
`useState` is a Hook that lets you add state to your functional components. Here is a basic example:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
In this example, `useState(0)` declares a state variable `count`, initialized with `0`. `setCount` is the method used to update the state variable.
`useEffect` lets you perform side effects in your function components. It is like `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` combined in class components.
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
return () => {
document.title = 'React App';
};
}, [count]);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
In this example, `useEffect` will run after every render when the `count` changes. The return statement in the `useEffect` block will run when the component is unmounted, acting as a cleanup mechanism.
`useContext` is a Hook used to create a context for sharing values like themes and authentication status between components.
import React, { useContext, createContext, useState } from 'react';
const ThemeContext = createContext();
function App() {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar() {
return (
<div>
<ThemedButton />
</div>
);
}
function ThemedButton() {
const { theme, setTheme } = useContext(ThemeContext);
return (
<button
onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}
style={{ backgroundColor: theme === 'light' ? '#fff' : '#333', color: theme === 'light' ? '#000' : '#fff' }}>
Toggle Theme
</button>
);
}
Here, `ThemeContext` provides a context that holds the current theme, and any component within this context can access the theme value and the `setTheme` function to toggle the theme.
`useReducer` is usually preferable to `useState` when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.
import React, { useReducer } from 'react';
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</>
);
}
Here, `useReducer` takes a `reducer` and an `initialState` and returns the current state paired with a `dispatch` method.
`useCallback` returns a memoized callback. It is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.
import React, { useState, useCallback } from 'react';
function App() {
const [count, setCount] = useState(0);
const increment = useCallback(() => {
setCount(count + 1);
}, [count]);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={increment}>Increment</button>
</div>
);
}
In this example, `useCallback` will return a memoized version of the increment function that only changes if `count` has changed.
`useMemo` is a Hook used to memorize the computed values. It will only recompute the memoized value when one of the dependencies has changed.
import React, { useState, useMemo } from 'react';
function App() {
const [count, setCount] = useState(0);
const [otherCount, setOtherCount] = useState(0);
const doubleCount = useMemo(() => {
console.log('Computation running...');
return 2 * count;
}, [count]);
return (
<div>
<p>Count: {count}, doubled: {doubleCount}</p>
<button onClick={() => setCount(count + 1)}>Increment Count</button>
<button onClick={() => setOtherCount(otherCount + 1)}>Increment Other Count</button>
</div>
);
}
Here, `doubleCount` is only recomputed when `count` changes, not when `otherCount` changes, thus optimizing performance.
Beyond the basic hooks, developers can also create custom hooks to extract component logic into reusable functions. Custom hooks are JavaScript functions whose names are prefixed with the word "use". Here’s a simple example of a custom hook that uses `useState` and `useEffect` to fetch data from an API:
import React, { useState, useEffect } from 'react';
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function fetchData() {
const response = await fetch(url);
const result = await response.json();
setData(result);
setLoading(false);
}
fetchData();
}, [url]);
return { data, loading };
}
function App() {
const { data, loading } = useFetch('https://api.example.com/data');
if (loading) return <p>Loading...</p>;
return <div>Data: {JSON.stringify(data)}</div>;
}
In this example, `useFetch` is a custom hook that fetches data from a given URL and returns the fetched data along with the loading status.
UPCET Exam
Click Here
SAAT Exam
Click Here
MHT CET Exam
Click Here
IPU CET Exam
Click Here
KCET Exam
Click Here
COMEDK UG Exam
Click Here
VITEEE Exam
Click Here
BITSAT
Click Here
DSAT: Dayanand Sagar Admission Test
Click Here
Career In Animation in india
Click Here
Merchant Navy Courses in india
Click Here
Interior Design Career in india
Click Here
UGC NET Exam
Click Here
B. Ed Exam
Click Here
AFCAT - Air Force Common Admission Test
Click Here
GATE Exam
Click Here
Joint Entrance Examination (JEE)
Click Here
Common Admission Test (CAT)
Click Here
CDS - Combined Defence Services Exam
Click Here