Managing State with Context API
The Context API in React provides a way to share state across the component tree without having to pass props manually at every level. It’s particularly useful for managing global state, such as user authentication, theme preferences, or language settings.
- createContext: The
createContext
function from React allows you to create a new context object. This context object consists of a Provider and a Consumer. - Provider: The Provider component is used to wrap the part of your component tree where you want to share the context. It accepts a value prop that provides the data to be shared.
- Consumer: The Consumer component is used within child components to access the data provided by the context. It uses a render prop pattern or the useContext hook to consume the context’s value.
import React, {
createContext,
useState
} from 'react';
// Create a context with initial state
const MyContext = createContext({
data: null,
updateData: () => { },
});
const MyProvider = ({ children }) => {
const [data, setData] = useState(null);
const updateData = newData => {
setData(newData);
};
return (
<MyContext.Provider value={{ data, updateData }}>
{children}
</MyContext.Provider>
);
};
export { MyContext, MyProvider };
Getting Started with React
ReactJS, often referred to as React, is a popular JavaScript library developed by Facebook for building user interfaces. It emphasizes a component-based architecture, where UIs are built using reusable components. React uses a declarative syntax to describe how UIs should look based on their state, simplifying development and enhancing code readability.
React also utilizes a virtual DOM to optimize rendering performance by minimizing actual DOM manipulations. React’s unidirectional data flow and rich ecosystem of libraries and tools have made it a go-to choice for frontend development, especially in building single-page applications (SPAs).
Table of Content
- Why ReactJS ?
- Setting Up Your Development Environment
- Understanding React Components
- Creating Your First React Component
- JSX (JavaScript XML)
- Working with Props and State
- Handling Events:
- Conditional Rendering
- Lists and Keys
- Styling React Components
- Introduction to React Hooks
- Building a Simple React Application
- Component Lifecycle
- React Router
- Managing State with Context API