This repo is an example of how to use React Hooks and Suspense together. It approaches examples of almost all hook APIs and also displays some other possible integration between them. It also shows how we can leverage TypeScript with React.
git clone <repo_url>
yarn
- Override types - look down.
yarn start
Override types:
-
Create missing
createRoot
type in @types/react-dom Inreact-moving-forward-example/node_modules/@types/react-dom/index
aftercreatePortal
add:export function createRoot(children: any): any;
-
Uncomment Suspense's maxDuration in @types/react In
react-moving-forward-example/node_modules/@types/react/index
search for maxDuration inside the Suspense type and uncomment maxDuration
Note: yarn is required, since we are using package.json's resolution feature to override the scheduler's version, npm doesn't provide that.
Note 2: The app fetches news articles from google news api, I've kept my google api key in the repo to facilitate the usage, however, there is a limit of 1000 requests per day, if you run out jsut create a new account and change the api key below. google news api
Hooks are a new feature proposal that lets you use state and other React features without writing a class. They’re currently in React v16.7.0-alpha and being discussed in an open RFC.
- useState
- useEffect
- useContext
- useReducer
- useMemo
- useRef
- useImperativeMethods
- useMutationEffect
- useLayoutEffect
Request data inside Function Components
const useGoogleNewsData = () => {
const [googleNews, setGoogleNews] = useState([]);
useEffect(() => {
fetchGoogleNews(setGoogleNews);
}, []);
return googleNews;
};
Minimalistic State shared with Context: Note that it's recommended to separate the Provider into two.
export const UserContextProvider: React.SFC<{}> = ({ children }) => {
const [state, dispatch] = useState(initialState);
const value = {
state,
dispatch,
};
return <UserContext.Provider value={value}>{children}</UserContext.Provider>;
};
Fetcher: A component that fetches and component resolution incorporated with Suspense.
<View>
<Text type='body'>Fetcher example</Text>
<Fetcher
url={googleNewsUrl}
mapData={(dt) => dt.articles}
onRender={({ data }: any) => <NewsList news={data} />}
onFallback={<p>Loading...</p>}
onFailure={<p>Failure</p>}
maxDuration={1000}
saveData={(dt) => null}
/>
</View>
-
RFC reactjs/rfcs#68
-
useCallback() invalidates too often in practice #14099 PR about it: facebook/react#14099
-
Provide more ways to bail out inside Hooks #14110 facebook/react#14110
-
Accessing hooks by using the second param of the function proposed by Leebyron reactjs/rfcs#68 (comment)
-
useContext updates all connected components independent if dependent value updated.