Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

react context

// ---------------- 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>
    )
}



 
PREVIOUS NEXT
Tagged: #react #context
ADD COMMENT
Topic
Name
7+6 =