Welcome to our in-depth tutorial on Context with Reducer in React JS! In this lesson, we'll explore how to manage state in a React application using the Context API and Reducer. By the end of this tutorial, you'll be able to handle complex state management scenarios in a practical and efficient way. Let's dive in!
š” Pro Tip: Context is a way to pass data through the component tree without having to pass props down manually at every level.
// Creating a Context
const MyContext = React.createContext();// Creating a Context Provider
function MyComponent() {
const [state, setState] = React.useState(initialState);
return (
<MyContext.Provider value={{ state, setState }}>
{/* Your components here */}
</MyContext.Provider>
);
}// Consuming the Context
function MyConsumer() {
const contextValue = React.useContext(MyContext);
// Access the state and functions provided by the Context Provider
const { state, setState } = contextValue;
// Use the state and functions in your component
return <div>{/* Your component logic here */}</div>;
}š Note: A reducer is a function that takes the current state and an action, and returns a new state. This is useful for handling complex state changes in a predictable manner.
// Creating a Reducer
function myReducer(state, action) {
switch (action.type) {
case 'UPDATE_STATE':
return { ...state, newState: action.newState };
default:
return state;
}
}// Creating a Context Provider with Reducer
function MyComponent() {
const [state, dispatch] = React.useReducer(myReducer, initialState);
return (
<MyContext.Provider value={{ state, dispatch }}>
{/* Your components here */}
</MyContext.Provider>
);
}// Updating state using dispatch
function MyConsumer() {
const { state, dispatch } = React.useContext(MyContext);
const handleClick = () => {
dispatch({ type: 'UPDATE_STATE', newState: newValue });
};
return <button onClick={handleClick}>Update State</button>;
}What is the purpose of Context in React?
What does a reducer do in React?
Keep learning and happy coding! š šÆ