Skip to content

Instantly share code, notes, and snippets.

@Lightnet
Created November 20, 2021 21:42
Show Gist options
  • Save Lightnet/5f6bec2fb37510b531a81bce455f53c1 to your computer and use it in GitHub Desktop.
Save Lightnet/5f6bec2fb37510b531a81bce455f53c1 to your computer and use it in GitHub Desktop.
react Context Provider example
import { createContext, useContext, useMemo, useState } from "react";
// create content variable for store data
export const ForumContext = createContext();
// check Provider root level top
export function useForum(){
const context = useContext(ForumContext);
if (!context) {
throw new Error(`useForum must be used within a UserContext`)
}
return context;
}
// create branch off forum
export function useBoard(){
const context = useContext(ForumContext);
if (!context) {
throw new Error(`useForum must be used within a UserContext`)
}
const {boardID, setBoardID} = context;
return {boardID, setBoardID};
}
// this context props top root level that pass to child component
export function ForumProvider(props){
const [forumID, setForumID] = useState('');
const [boardID, setBoardID] = useState('');
const [postID, setPostID] = useState('');
const [commentID, setCommentID] = useState('');
const value = useMemo(()=> ({
forumID,setForumID,
boardID,setBoardID,
postID,setPostID,
commentID,setCommentID,
}),[forumID,boardID,postID,commentID]);
return <ForumContext.Provider value={value} {...props} />
}
//... child
// import {useForum} from "../forumprovider"
function ForumSection(){
const {forumID, setForumID} = useForum();
const {boardID, setBoardID} = useBoard();
return (<>
<label> Forum </label>
</>)
}
//... app root area
return (<>
<ForumProvider>
<ForumSection />
</ForumProvider>
</>)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment