Epic react course key takeaways - useState lazy load and react hook flow

Learning react hooks and patterns from Kent C Dodds Epic React course

About a month ago I’ve started to slowly chip away at Kent C Dodds Epic React course, that was gratefully funded by Open Universities.

Although I’ve been building apps for production in React for a few years, I never really felt confident that I understood all the optimisations and craved to learn some useful patterns.

It was my intention to document some of the learnings here, so that I can refer back to them (if any), and after doing a few modules I’m greatly to share some things. Some of them may be broken up in different posts to prevent an overly large post.

Calling useState with a function for Lazy Loading

After visiting the React documentation, it was confirmed that this was not mentioned anywhere. Not sure why but it could be pretty useful, in particular to a situation outlined below. Every time we invoke useState, we can supply a function instead of a value. This function is the lazy initialiser and can be used for situations where setting initial state is a little more expensive than just setting a hardcoded value. One example used in the course was reading from local storage and deserializing an object:

function useLocalStorage(
	key,
	defaultValue = '',
	{ serialize = JSON.stringify, deserialize = JSON.parse } = {}
) {
	const [value, setValue] = React.useState(() => {
		// Lazy initialiser
		const localStorageValue = window.localStorage.getItem(key);
		if (localStorageValue) {
			return deserialize(localStorageValue);
		}

		return typeof defaultValue === 'function' ? defaultValue() : defaultValue;
	});

	const prevKeyRef = React.useRef(key);

	React.useEffect(() => {
		const prevKey = prevKeyRef.current;
		if (prevKey !== key) {
			window.localStorage.removeItem(prevKey);
		}

		prevKeyRef.current = key;
		window.localStorage.setItem(key, serialize(value));
	}, [key, value, serialize]);

	return [value, setValue];
}

React Hook flow Diagram

Will be back for more next time.