Introduction to React Hooks
What are React Hooks?
React Hooks are a feature introduced in React 16.8 that allows you to use state and other React features in functional components. Prior to hooks, stateful logic was only possible in class components using lifecycle methods. With hooks, you can manage state, side effects, and context directly within functional components, enabling cleaner and more concise code.
useState Hook
The useState
hook allows you to add state to functional components. It returns an array with two elements:
the current state value and a function to update that value. By calling the update function, React will re-render the
component with the new state. Here's an example:
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
return (
<div>
Count: {count}
<button onClick={increment}>Increment</button>
</div>
);
};
useEffect Hook
The useEffect
hook allows you to perform side effects in functional components. It takes a function as its
first argument, which will be executed after the component renders. Common use cases include fetching data from an API,
subscribing to events, or cleaning up resources. Here's an example:
import React, { useState, useEffect } from 'react';
const Timer = () => {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(prevSeconds => prevSeconds + 1);
}, 1000);
return () => {
clearInterval(interval);
};
}, []);
return (
<div>
Seconds: {seconds}
</div>
);
};
useContext Hook
The useContext
hook allows you to access the value of a context directly within a functional component.
It takes a context object created by React.createContext
and returns its current value. Here's an example:
import React, { useContext } from 'react';
import ThemeContext from './ThemeContext';
const Button = () => {
const theme = useContext(ThemeContext);
return (
<button style={{ background: theme.background, color: theme.foreground }}>
Themed Button
</button>
);
};
useReducer Hook
The useReducer
hook is an alternative to useState
for managing more complex state
logic. It accepts a reducer function and an initial state, and returns the current state and a dispatch function.
The reducer function handles state updates based on dispatched actions. Here's an example:
import React, { useReducer } from 'react';
const initialState = { count: 0 };
const reducer = (state, action) => {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
return state;
}
};
const Counter = () => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
Count: {state.count}
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
<button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
</div>
);
};
useCallback Hook
The useCallback
hook is used to memoize callback functions in order to prevent unnecessary re-renders in
child components. It takes a callback function and a dependency array, and returns a memoized version of the callback.
Here's an example:
import React, { useState, useCallback } from 'react';
const Button = () => {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
setCount(count + 1);
}, [count]);
return (
<div>
Count: {count}
<button onClick={handleClick}>Increment</button>
</div>
);
};
useMemo Hook
The useMemo
hook is used to memoize the result of a computation and avoid unnecessary re-computations.
It takes a function and a dependency array, and returns the memoized result. This can be useful for expensive
calculations or deriving values from other state or props. Here's an example:
import React, { useState, useMemo } from 'react';
const ExpensiveComponent = () => {
const [count, setCount] = useState(0);
const expensiveResult = useMemo(() => {
// Perform expensive computation here
return computeExpensiveResult(count);
}, [count]);
return (
<div>
Count: {count}
<div>Expensive Result: {expensiveResult}</div>
</div>
);
};
useRef Hook
The useRef
hook allows you to create a mutable value that persists across renders. It returns a mutable
ref object with a .current
property. This can be useful for accessing or manipulating DOM elements,
storing previous values, or triggering imperative actions. Here's an example:
import React, { useRef } from 'react';
const Input = () => {
const inputRef = useRef(null);
const focusInput = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={focusInput}>Focus Input</button>
</div>
);
};
Conclusion
React Hooks have revolutionized the way we write components in React. They provide a simpler and more elegant way to
manage state and side effects within functional components. By leveraging hooks such as useState
,
useEffect
, useContext
, useReducer
, useCallback
,
useMemo
, and useRef
, you can build powerful and flexible React applications with
cleaner and more concise code.
Comments
Post a Comment