Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
Context in React
Next article icon

What is the React Context API?

Last Updated : 10 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In the React ecosystem, as your application grows, passing data down through component hierarchies can become cumbersome. This is where the Context API steps in, providing a centralized way to manage state across components.

Table of Content

  • What is the Context API?
  • How Context API Works:
  • Steps to Create a Simple To-Do List with React Context API:

What is the Context API?

At its core, the Context API is a mechanism that allows you to share specific information (like state or functions) with multiple components, eliminating the need for prop drilling.

The React Context API is a powerful tool for efficient state management, offering a cleaner alternative to prop drilling and enhancing overall code organization.

How Context API Works:

1. Creating a Context

The process begins by creating a context using the createContext() method. This serves as a blueprint for the shared data.

JavaScript
/ Creating a context const MyContext = React.createContext(); 

2. Providing the Context

The context provider, wrapped around components requiring access to shared data, is established using the Provider

JavaScript
// Providing the context value function MyApp() {   return (     <MyContext.Provider value={/* your shared value */}>       {/* Components that can access the context value */}     </MyContext.Provider>   ); } 

3. Consuming the Context

JavaScript
function AnotherComponent() {   const contextValue = React.useContext(MyContext);    // Now, contextValue contains the shared value } 

Components nested within the provider can consume the shared data using the useContext hook or the Consumer component.

Steps to Create a Simple To-Do List with React Context API:

Let's create a straightforward project - a to-do list application using React and the Context API. This project will showcase how the Context API can simplify state management in a real-world scenario.

Step 1: Start by creating a new React app using Create React App.

npx create-react-app todo-list-context

Step 2: Navigate to the root directry of project using the following the command.

cd todo-list-context

Project Structure:

Screenshot-from-2024-02-04-13-10-15
Project Structure of todo list

package.json

 "dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"redux": "^5.0.1",
"web-vitals": "^2.1.4"
}
  • In your src/index.js, wrap your App component with the TodoProvider.
  • Now src/components/TodoForm.js , let's create components to interact with the to-do list.
  • Now its turn for src/components/TodoList.js
  • Now, in your src/App.js, use the TodoForm and TodoList components.
JavaScript
// TodoContext.js import React, { createContext, useState }     from 'react'; const TodoContext = createContext(); const TodoProvider = ({ children }) => {     const [todos, setTodos] = useState([]);     const addTodo = (text) => {         setTodos([...todos, { text, id: Date.now() }]);     };     const removeTodo = (id) => {         setTodos(todos.filter((todo) => todo.id !== id));     };     return (         <TodoContext.Provider value={{             todos,             addTodo, removeTodo         }}>             {children}         </TodoContext.Provider>     ); }; export { TodoProvider, TodoContext }; 
JavaScript
// index.js import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import { TodoProvider } from './TodoContext'; ReactDOM.render(   <React.StrictMode>     <TodoProvider>       <App />     </TodoProvider>   </React.StrictMode>,   document.getElementById('root') ); 
JavaScript
// TodoForm.js import React, { useState, useContext } from 'react'; import { TodoContext } from './TodoContext'; const TodoForm = () => {     const { addTodo } = useContext(TodoContext);     const [text, setText] = useState('');     const handleSubmit = (e) => {         e.preventDefault();         addTodo(text);         setText('');     };     return (         <form onSubmit={handleSubmit}>             <input                 type="text"                 value={text}                 onChange={(e) => setText(e.target.value)}                 placeholder="Add a new todo"             />             <button type="submit">Add Todo</button>         </form>     ); }; export default TodoForm; 
JavaScript
// TodoList.js import React, { useContext } from 'react'; import { TodoContext } from './TodoContext'; const TodoList = () => {     const { todos, removeTodo } = useContext(TodoContext);     return (         <ul>             {todos.map((todo) => (                 <li key={todo.id}>                     {todo.text}                     <button onClick={() =>                         removeTodo(todo.id)}>Remove</button>                 </li>             ))}         </ul>     ); }; export default TodoList; 
JavaScript
// App.js import React from 'react'; import TodoForm from './TodoForm'; import TodoList from './TodoList';  const App = () => {   return (     <div>       <h1>My Todo List</h1>       <TodoForm />       <TodoList />     </div>   ); }; export default App; 

Start your application using the following command.

npm start

Output:

Screenshot-from-2024-02-04-13-07-33
todo list app

Next Article
Context in React
author
isandeep2183
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • React-Questions

Similar Reads

  • What is react-router-dom ?
    React Router DOM is an npm package that enables you to implement dynamic routing in a web app. It allows you to display pages and allow users to navigate them. It is a fully-featured client and server-side routing library for React. React Router Dom is used to build single-page applications i.e. app
    6 min read
  • Context in React
    Context in React is used to share the data through the React Components without passing the props manually for every level of the component tree. It allows the data to be accessed globally throughout the application and enable efficient state management. In this article, you will be introduced to Re
    4 min read
  • Context API with useContext Hook
    React Context API is a very helpful feature that enables the sharing of state across components without the need for prop drilling. It simplifies state management and makes it easier to pass data down the component tree. In this article we will explore the Context API and demonstrate how to use it w
    3 min read
  • What is the use of React Context in React-Redux?
    React Context is a feature that React provides us to manage states required in multiple components. Redux is also a state management library and solves the same problem that React Context does but in a different way. In this article, we will see in detail what is react context, why and how to use it
    5 min read
  • What are the features of ReactJS ?
    Created by Facebook, ReactJS is a JavaScript library designed for crafting dynamic and interactive applications, elevating UI/UX for web and mobile platforms. Operating as an open-source, component-based front-end library, React is dedicated to UI design and streamlines code debugging by employing a
    4 min read
  • What are the advantages of React.js ?
    React.js is a popular JavaScript library used for building dynamic and interactive user interfaces. It has become a go-to tool for developers due to its efficient architecture, high performance, and ease of use. This article highlights the key advantages of using React.js for web development and exp
    5 min read
  • What are synthetic events in ReactJS ?
    In order to work as a cross-browser application, React has created a wrapper same as the native browser in order to avoid creating multiple implementations for multiple methods for multiple browsers, creating common names for all events across browsers. PrerequisitesJavaScript & DOM manupulation
    3 min read
  • What are Provider and Consumer in the Context API ?
    Context API is a term that is created to pass as a global variable and can be accessed anywhere in the code. It is another way to pass props from child to parent i.e. known as "prop drilling". It has two main components "The Context Provider " and "The Context Consumer". Table of Content The Context
    3 min read
  • What are props in React Native ?
    Props are used to provide properties to the components using which they can be modified and customized. These properties are passed to the components when the component is created. Props are used in both user-defined and default components to extend their functionality. These props are immutable and
    5 min read
  • What are the 3 core concepts of React Redux ?
    Redux is a widely-used state management library that helps in managing the state in our projects. However, it comes with its own terminologies and jargon that can be confusing for beginners. Essentially, Redux comprises of three core concepts: actions, reducers, and store. In this article, we will c
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences