Introduction
In this blog post, we’ll delve into three advanced React Hooks – `useContext`, `useImperativeHandle`, and `useReducer`. These Hooks enable efficient component management and state handling, helping to build more complex and scalable React applications.
useContext
`useContext` allows you to share state and other data between components without having to pass props down manually from a parent to every child. It creates a React context and returns the current context value.
Here’s a basic example:
“`javascript
import React, { createContext, useContext } from ‘react’;
const MyContext = createContext();
const MyProvider = MyContext.Provider;
const MyConsumer = MyContext.Consumer;
function App() {
const [value, setValue] = React.useState(‘default value’);
return (
);
}
function MyComponent() {
const value = useContext(MyContext);
// Use the value here
return
;
}
function MyOtherComponent() {
return
;
}
“`
useImperativeHandle
`useImperativeHandle` lets you attach a ref instance to a custom React component and give it instance methods. This can be useful when integrating with legacy code or when using third-party libraries that require direct access to the underlying DOM node or instance.
Here’s an example:
“`javascript
import React, { forwardRef, useImperativeHandle } from ‘react’;
const FancyButton = forwardRef((props, ref) => {
const inputRef = React.useRef(null);
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
},
}));
return ;
});
function App() {
const buttonRef = React.useRef(null);
return
}
// Now you can call focus on the button ref
ReactDOM.render(
buttonRef.current.focus();
“`
useReducer
`useReducer` is a Hook that helps you manage complex state patterns in functions components. It accepts a reducer function and an initial state value. The reducer function should be a pure function that takes the current state and an action, and returns the next state.
Here’s an example using `useReducer` to manage the state of a form:
“`javascript
import React, { useReducer } from ‘react’;
const initialFormState = { firstName: ”, lastName: ” };
const reducer = (state, action) => {
switch (action.type) {
case ‘UPDATE_FIRST_NAME’:
return { …state, firstName: action.payload };
case ‘UPDATE_LAST_NAME’:
return { …state, lastName: action.payload };
default:
throw new Error();
}
};
function Form() {
const [formState, dispatch] = useReducer(reducer, initialFormState);
const handleFirstNameChange = (event) => {
dispatch({ type: ‘UPDATE_FIRST_NAME’, payload: event.target.value });
};
const handleLastNameChange = (event) => {
dispatch({ type: