[React] Improve developer experience for accessing context with a custom React hook
Posted Answer1215
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[React] Improve developer experience for accessing context with a custom React hook相关的知识,希望对你有一定的参考价值。
In this lesson, we create a custom hook that wraps the useContext
hook and returns its value, as well as more useful error messaging if a context provider is missing. This simple addition brings very elegant ergonomics to access context from any component.
providers/app-state.js
import React, { createContext, useContext, useState } from "react"; // Context const AppStateContext = createContext(); // Provider export function AppStateProvider({ children }) { const [searchValue, setSearchValue] = useState(""); const [shortList, setShortList] = useState([]); // The context value object const value = { searchValue, setSearchValue, shortList, setShortList }; return ( <AppStateContext.Provider value={value}> {children} </AppStateContext.Provider> ); } // Custom hook export function useAppState() { const context = useContext(AppStateContext); if (!context) { throw new Error( "You probably forgot the <AppStateProvider> context provider!" ); } return context; }
Provider it:
// index.js // React import React from "react"; import ReactDOM from "react-dom"; // CSS import "normalize-css"; import "./css/styles.css"; // Components import App from "./App"; import { NamesProvider } from "./providers/names"; import { AppStateProvider } from "./providers/app-state"; ReactDOM.render( <React.StrictMode> <NamesProvider> <AppStateProvider> <App /> </AppStateProvider> </NamesProvider> </React.StrictMode>, document.getElementById("root") );
Consume it:
import React from "react"; import { NamesList } from "./names-list"; import { useNames } from "../providers/names"; import { useAppState } from "../providers/app-state"; export function NamePicker() { const names = useNames(); const { searchValue, shortList, setShortList } = useAppState(); const filteredNames = names .filter(entry => entry.name.toLowerCase().includes(searchValue.toLowerCase()) ) .filter(entry => !shortList.includes(entry.id)); function addToShortList(id) { setShortList([...shortList, id]); } return <NamesList namesList={filteredNames} onItemClick={addToShortList} />; }
以上是关于[React] Improve developer experience for accessing context with a custom React hook的主要内容,如果未能解决你的问题,请参考以下文章
[React Testing] Use Generated Data in Tests with tests-data-bot to Improve Test Maintainability(代码片段
babel.js, react-dom.development.js, react-development.js
smaller programs should improve performance