links: React MOC


How to conditionally load components using Suspense

I had a problem where I would like to load storybook only in dev mode. I need a way to load these components lazily and conditionally.

Here’s an example of loading StoryBook only in Dev mode

import React, { useState, useCallback, Suspense, lazy } from 'react';
import { ActivityIndicator, AppRegistry, DevSettings } from 'react-native';
...
 
const RootComponent = () => {
	const [storybookActive, setStorybookActive] = useState(false);
	const toggleStorybook = useCallback(
		() => setStorybookActive(active => !active),
		[],
	);
 
	useMountEffect(() => {
		if (__DEV__) {
			DevSettings.addMenuItem('Toggle StoryBook', toggleStorybook);
		}
	});
 
	if (storybookActive) {
		const StorybookUIRoot = lazy(() => import('./storybook'));
		return (
			<Suspense fallback={<ActivityIndicator />}>
				<StorybookUIRoot />
			</Suspense>
		);
	}
 
	return <App />;
};

tags: react , lazy , suspense

sources: