How to use Context Api into your Projects

Atiq ur rehman
3 min readSep 5, 2023

With Context Api ()

Creating a counter and a todo list using React and possibly the React Context API and some React hooks. I’ll provide a basic example of how you can achieve this, but keep in mind that this is a simplified example, and you can expand upon it to meet your specific requirements.

  1. Set up your React project if you haven’t already:
npx create-react-app counter-todo-app
cd counter-todo-app
npm startjav

2. Create a Context for Counter and Todo:

// CounterContext.js
import React, { createContext, useContext, useReducer } from 'react';

// Initial state for the counter
const counterInitialState = { count: 0 };

// Reducer for the counter
const counterReducer = (state, action) => {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
default:
return state;
}
};

// Initial state for the todo list
const todoInitialState = { todos: [] };

// Reducer for the todo list
const todoReducer = (state, action) => {
switch (action.type) {
case 'ADD_TODO':
return { todos: [...state.todos, action.payload] };
case 'REMOVE_TODO':
return { todos: state.todos.filter((todo) => todo.id !== action.payload) };
default:
return state;
}
};

const CounterContext = createContext();

export const CounterProvider = ({ children }) => {
const [counterState, counterDispatch] = useReducer(counterReducer, counterInitialState);
const [todoState, todoDispatch] = useReducer(todoReducer, todoInitialState);

return (
<CounterContext.Provider value={{ counterState, counterDispatch, todoState, todoDispatch }}>
{children}
</CounterContext.Provider>
);
};

export const useCounter = () => {
const context = useContext(CounterContext);
if (!context) {
throw new Error('useCounter must be used within a CounterProvider');
}
return context;
};

3. Create components for the counter and todo list:

// Counter.js
import React from 'react';
import { useCounter } from './CounterContext';

const Counter = () => {
const { counterState, counterDispatch } = useCounter();

return (
<div>
<h2>Counter: {counterState.count}</h2>
<button onClick={() => counterDispatch({ type: 'INCREMENT' })}>Increment</button>
<button onClick={() => counterDispatch({ type: 'DECREMENT' })}>Decrement</button>
</div>
);
};

export default Counter;

Todo Component

// TodoList.js
import React, { useState } from 'react';
import { useCounter } from './CounterContext';

const TodoList = () => {
const { todoState, todoDispatch } = useCounter();
const [todoText, setTodoText] = useState('');

const addTodo = () => {
const newTodo = { id: Date.now(), text: todoText };
todoDispatch({ type: 'ADD_TODO', payload: newTodo });
setTodoText('');
};

const removeTodo = (id) => {
todoDispatch({ type: 'REMOVE_TODO', payload: id });
};

return (
<div>
<h2>Todo List</h2>
<ul>
{todoState.todos.map((todo) => (
<li key={todo.id}>
{todo.text} <button onClick={() => removeTodo(todo.id)}>Remove</button>
</li>
))}
</ul>
<input
type="text"
placeholder="Enter a new todo"
value={todoText}
onChange={(e) => setTodoText(e.target.value)}
/>
<button onClick={addTodo}>Add Todo</button>
</div>
);
};

export default TodoList;

4. Finally, use these components in your main App component:

// App.js
import React from 'react';
import './App.css';
import { CounterProvider } from './CounterContext';
import Counter from './Counter';
import TodoList from './TodoList';

function App() {
return (
<CounterProvider>
<div className="App">
<Counter />
<TodoList />
</div>
</CounterProvider>
);
}

export default App;

Are you ready to embark on a journey that will transform you into a ReactJS maestro? Look no further! Our ReactJS Programming Book is your ultimate companion for mastering this powerful JavaScript library. 🚀

📚 Why Choose Our ReactJS Programming Book?

🧠 Comprehensive Learning: Dive deep into ReactJS with a structured, step-by-step approach that takes you from novice to pro.

👩‍💻 Hands-On Practice: Learn by doing! With real-world projects and exercises, you’ll gain practical experience that sets you apart.

📈 Stay Updated: React evolves fast, and so do we! Our book keeps you up-to-date with the latest best practices and features.

🎯 Solve Real Problems: Tackle common React challenges head-on with expert tips and solutions.

📖 In-Depth Content: We cover React fundamentals, advanced concepts, and state-of-the-art techniques, ensuring you’re well-rounded.

👥 Community Support: Join our thriving online community of React enthusiasts for networking, advice, and collaboration.

🏆 Achieve Your Goals: Whether you aim to land a high-paying job, build your dream app, or stay ahead of the curve, our book is your ticket to success.

🌐 Global Appeal: ReactJS is used worldwide. Our book is suitable for developers of all backgrounds and skill levels.

Don’t miss out on this opportunity to become a ReactJS expert! Grab your copy now and unlock the doors to endless possibilities. 🌟

👉 Order Now

🎁 Bonus: Get exclusive access to valuable resources, code samples, and updates when you purchase our ReactJS Programming Book!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Atiq ur rehman
Atiq ur rehman

No responses yet

Write a response