#16 React JS Tutorial 2024 | Context API with useReducer | Hindi
In this tutorial, we will learn about how to use Context API with useReducer in React JS. Context API is a way to pass data through the component tree without having to pass props down manually at every level. useReducer is a hook that is used for state management in React applications.
Step 1: Creating a Context
First, we need to create a context using the createContext() function from React.
const MyContext = React.createContext();
Step 2: Creating a Reducer
Next, we need to create a reducer function that will handle the state changes in our application.
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:
return state;
}
}
Step 3: Using Context API with useReducer
Now, we can use the context and reducer in our component to manage the state.
const [state, dispatch] = useReducer(reducer, initialState);
return (
<MyContext.Provider value={{ state, dispatch }}>
{children}
</MyContext.Provider>
);
Step 4: Accessing State and Dispatch
In order to access the state and dispatch functions in our components, we can use the useContext() hook.
const { state, dispatch } = useContext(MyContext);
By following these steps, you can effectively use Context API with useReducer in your React JS applications. This allows for a more efficient way to manage state and pass data between components.
Woww uploaded full series in one day