context is just a set of variables and functions, you will use context if multiples files needs the same variables or functions and when multiple of react component needs the same variables or functions
for me the best tool for context/state management is recoil.js, ohh i don't know if it is just recoil but UI/UX loading is faster if you set the data to state before you populate.
xxxxxxxxxx
// ---------------- Parent.js
import {createContext , useState} from "react";
let contextName = createContext( ) // you can optionally pass it a default value // it returns a "provider" object
let Parent = () => {
let [count , setCount] = useState() // returns an [ state variable , state setter fn]. you can pass useState() a default value too
// the stateSetter function is async
return (
<div>
<contextName.Provider value={ {count , setCount } } > // you can send multiple things across to the consumers by adding them in a single object
<B/>
</contextName.Provider>
</div>
)
}
export {contextName};
export default Parent;
// file that consumes the context
// --------- Child.js -----------
import {useContext} from "react"; // import the useContext hook that will allow you to actually use the created and imported context
import {contextName } from "./Parent"; // import the particular context that you want to use
let Child = () => {
let value = useContext(contextName);
return (
<div> {value} </div>
)
}
xxxxxxxxxx
import React from "react";
// 1. Create context - storing values
export const CartContext = React.createContext();
// CartContext.Provider
// this is you create that context box
// Provider
export function CartContextProvider({ children }) {
const [cartCount, setCartCount] = React.useState(0);
const handleCartUpdate = (val) => {
setCartCount(cartCount + val);
};
const handleDec=(val)=>{
setCartCount(cartCount + val);
}
return (
<CartContext.Provider value={{ cartCount, handleCartUpdate,handleDec }}>
{children}
</CartContext.Provider>
);
}
=====================navbar.jsx
import React from "react";
import { CartContext } from "../Context/CardContexr";
const Navbar = () => {
const { cartCount } = React.useContext(CartContext);
const{handleCartUpdate}= React.useContext(CartContext)
// const { theme } = React.useContext(ThemeContext);
return <>
<h1 >Cart Count : {cartCount}</h1>
<button onClick={()=>{handleCartUpdate(1)}} >change</button>
</>
};
export default Navbar;
xxxxxxxxxx
DEFINITION::::::
Context provide a way to pass data through the component tree without
having to pass down manually at every level
HOW TO USE::::::
DECLARATION:::
const MyContext = React.createContext()
Creating a new Context for each unique piece of data that needs to be available
throughout your component data
const LocaleContext = React.createContext()
Properties of LocaleContext --------
LocaleContext.Provider
LocaleContext.Consumer
What is a Provider
Allows us to "declare the data that we want available throughout our
component tree"
What is a Consumer
Allows "any component in the tree that needs that data to be able to
subscibe to it"
How to use Provider
<MyContext.Provider value={data}>
<App />
</MyContext.Provider>
xxxxxxxxxx
/*
The React Context API uses a Provider and Consumer pattern to
share data throughout an application. The provider role
is played by a React componentthat makes data available to
its descendant components.
When one of those descendants accesses the shared data,
it becomes a consumer.
To use the React Context API, we start by creating a React
context object, a named object created by the
React.createContext() function.
*/
const MyContext = React.createContext();
/*
Context objects include a .Provider property that is
a React component. It takes in a value prop to be stored
in the context.
*/
<MyContext.Provider value="Hello world!">
<ChildComponent />
</MyContext.Provider>
/*
That value — in this case, the string "Hello world!" — is
available to all its descendent components. Descendent
components — in this case, ChildComponent — can then retrieve
the context’s value with React’s useContext() hook.
*/
import { useContext } from 'react';
import { MyContext } from './MyContext.js'
const ChildComponent = () => {
const value = useContext(MyContext);
return <p>{value}</p>;
}
// Renders <p>Hello, world!</p>
/*
The useContext() hook accepts the context object as an
argument and returns the current value
of the context. Rejoice — prop drilling that value is
no longer needed!
Note: If a component attempts to use a context that
isn’t provided by one of its ancestors, useContext() will return null.
*/
xxxxxxxxxx
//React context allows us to pass data to our component tree without using props.
To use Context, we use the createContext function from React.
The created context includes a Provider and a Consumer property, which are each components.
We wrap the Provider around the component tree that we want to pass
the given value down.
Next, we place the Consumer in the component we want to consume the value.
import { createContext } from 'react';
const NameContext = createContext('');
function App() {
return (
<NameContext.Provider value="John Doe">
<Body />
<NameContext.Provider>
);
}
function Body() {
return <Greeting />;
}
function Greeting() {
return (
<NameContext.Consumer>
{name => <h1>Welcome, {name}</h1>}
//we got function with name argument which we will use
</NameContext.Consumer>
);
}
//using useContext hook
rewrite our example from earlier, using the useContext hook:
import { createContext, useContext } from 'react';
const NameContext = createContext('');
function App() {
return (
<NameContext.Provider value="John Doe">
<Body />
<NameContext.Provider>
);
}
function Body() {
return <Greeting />;
}
function Greeting() {
const name = useContext(NameContext);
//useContext with name of context
return (
<h1>Welcome, {name}</h1>
);
}
xxxxxxxxxx
import React, { useState } from 'react'
const GlobalStateContext = React.createContext({ })
export const GlobalStateProvider = ({ children }) => {
const [config, setConfig] = useState({
projectInfo: ''
})
const [projectFile, setProjectFile] = useState('./test.cpp')
const [executionState, setExecutionState] = useState("NoProject")
return (
<GlobalStateContext.Provider
value={{
executionState,
config,
projectFile,
setExecutionState,
setConfig,
setProjectFile,
}}
>
{children}
</GlobalStateContext.Provider>
)
}
export default GlobalStateContext
xxxxxxxxxx
import React, { createContext, useReducer } from "react";
import reducer, { initialState } from "./reducer";
export let todoContext = createContext({});
export default function Provider({ children }) {
const [state, dispatch] = useReducer(reducer, initialState);
const values = {
state,
dispatch
};
return (
<>
<todoContext.Provider value={values}>
{children}
</todoContext.Provider>
</>
);
}
xxxxxxxxxx
import { createContext, useContext, useReducer } from "react";
const Actions = {
SET_ITEMS: "SET_ITEMS",
};
const reducer = (state, action) => {
if (action.type === Actions.SET_ITEMS) {
return { state, items: action.payload };
}
return state;
};
const initialState = {
items: []
};
const SimpleContext = createContext(initialState);
export const useSimpleContext = () => useContext(SimpleContext);
export const SimpleProvider = ({ children }) => {
const [state, dispatch] = useReducer(reducer, initialState);
function setItems(items) {
dispatch({ type: Actions.SET_ITEMS, payload: items });
}
return <SimpleContext.Provider value={{ state, setItems }}>{children}</SimpleContext.Provider>;
};
xxxxxxxxxx
// Theme context, default to light theme
const ThemeContext = React.createContext('light');
// Signed-in user context
const UserContext = React.createContext({
name: 'Guest',
});
class App extends React.Component {
render() {
const {signedInUser, theme} = this.props;
// App component that provides initial context values
return (
<ThemeContext.Provider value={theme}>
<UserContext.Provider value={signedInUser}>
<Layout />
</UserContext.Provider>
</ThemeContext.Provider>
);
}
}
function Layout() {
return (
<div>
<Sidebar />
<Content />
</div>
);
}
// A component may consume multiple contexts
function Content() {
return (
<ThemeContext.Consumer>
{theme => (
<UserContext.Consumer>
{user => (
<ProfilePage user={user} theme={theme} />
)}
</UserContext.Consumer>
)}
</ThemeContext.Consumer>
);
}
xxxxxxxxxx
import React from "react";
export const ThemeContext = React.createContext();
export default class Theme extends React.Component {
constructor(props) {
super(props);
this.state = {
mode: "dark",
toggleMode: this.toggleMode
}
}
toggleMode = () => {
console.log('yes');
this.setState({
mode: this.state.mode === 'dark' ? 'light' : 'dark'
});
}
render() {
return (
<ThemeContext.Provider value={this.state} >
{this.props.children}
</ThemeContext.Provider>
)
}
}