React Hooks & useContext: Is This a Good Pattern?

时间:2019-02-24 03:12:11

标签: reactjs react-hooks react-state-management react-state

I'm studying useContext with React Hooks. I would like to pass a single object containing application state to context Consumers, e.g.:

<AppContextProvider.Provider value={AppState}>
  {props.children}
</AppContextProvider.Provider>

Of course, I will need to pass some getters and setters to enable child components to update application state.

Is this pattern an efficient approach -- is there a better pattern?

const AppContext = React.createContext();

function AppContextProvider(props) {
    const AppState = {
        aVideoCallIsLive: [get, set] = useState(false),
        channelName: [get, set] = useState(null),
        localVideoStream: [get, set] = useState(null),
        selectedBottomNavIndex: [get, set] = useState(-1),
        loginDialogIsOpen: [get, set] = useState(false),
    }
}

1 个答案:

答案 0 :(得分:1)

为什么不使用reducer并传递单个调度函数?

我相信它也建议您通过状态和分发是分开的上下文,否则调用分发将导致上下文中的所有内容重新呈现。

https://reactjs.org/docs/hooks-faq.html#how-to-avoid-passing-callbacks-down

https://reactjs.org/docs/hooks-reference.html#usereducer