Context with Reducer in React JS

beginner
25 min

Context with Reducer in React JS

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!

Understanding Context

šŸ’” Pro Tip: Context is a way to pass data through the component tree without having to pass props down manually at every level.

jsx
// Creating a Context const MyContext = React.createContext();

Using Context

jsx
// Creating a Context Provider function MyComponent() { const [state, setState] = React.useState(initialState); return ( <MyContext.Provider value={{ state, setState }}> {/* Your components here */} </MyContext.Provider> ); }

Accessing Context

jsx
// 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>; }

Introducing Reducer

šŸ“ 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.

jsx
// Creating a Reducer function myReducer(state, action) { switch (action.type) { case 'UPDATE_STATE': return { ...state, newState: action.newState }; default: return state; } }

Combining Context and Reducer

jsx
// 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 with Reducer

jsx
// 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>; }
Quick Quiz
Question 1 of 1

What is the purpose of Context in React?

Quick Quiz
Question 1 of 1

What does a reducer do in React?

Keep learning and happy coding! šŸš€ šŸŽÆ