简体   繁体   中英

React - What is the Best Way to use Multiple createContexts?

I've just learned about the createContext hook and I'm wondering what's the best approach to using multiple contexts globally throughout the project.

From what I've seen if you want to create and use multiple contexts it looks kinda messy having multiple nested Context tags and I'm wondering if there is a cleaner looking way of doing this?

(Example of how I think a project using four contexts would look)

import React, { createContext, useState } from "react";

export const OneContext = createContext();
export const TwoContext = createContext();
export const ThreeContext = createContext();
export const FourContext = createContext();

export default function App(){
    const [one, setOne] = useState(null);
    const [two, setTwo] = useState(null);
    const [three, setThree] = useState(null);
    const [four, setFour] = useState(null);

   return(
        <>
            <OneContext.Provider value={one}>
                <TwoContext.Provider value={two}>
                    <ThreeContext.Provider value={three}>
                        <FourContext.Provider value={four}>            
                            "Insert components here"
                        <FourContext.Provider />
                    <ThreeContext.Provider />
                <TwoContext.Provider />
            <OneContext.Provider />
        </>
   )
}

You can do something like that

<AppContext.Provider
  value={{
    oneCTX: [one, setOne],
    twoCTX: [two, setTwo],
    threeCTX: [three,setThree]
  }}
>
  {props.children}
</AppContext.Provider>

on the other files, you can call them like this, Import AppContext from the context.js file first, then do that

const { oneCTX } = useContext(AppContext);
const [one, setOne] = loggedUserCTX;

useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.

import React, { createContext, useReducer } from "react";

const OneContext = createContext();

const initialState = {one:null, two:null, three:null, four:null};

function reducer(state, action) {
  return {
    ...state,
    [action.type]: action.payload
  }
}

export default function App(){
   const stateAndDispatch = useReducer(reducer, initialState)
   return(
        <>
            <OneContext.Provider value={stateAndDispatch}>       
                "Insert components here"
            <OneContext.Provider />
        </>
   )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM