Member-only story

Recoil Project Structure Best Practices

Wesley Rast
8 min readDec 11, 2020

--

Photo by Matthew Henry from Burst

Recoil is React’s best solution so far for global state management. It’s lightweight, simple and performant approach to communicating between components provides a better experience for both the user and the developer than previous libraries like Redux or RxJS. However, the project is very new, and lacks the years of community involvement to produce standard best practices for setting up your project with an eye towards scalability. What follows here is what I’ve found to work best for a large React Native and React Native Web hybrid application.

Problems With Prevailing Structure

Most of the Recoil examples I’ve seen others produce on the web create a structure similar to this:

A single directory is created under /src/recoil which is then split into /atoms and /selectors. This works, but there’s a fundamental problem here that isn’t apparent when you first begin working with Recoil. Let me start with an example of why this isn’t ideal.

Here, we have the /atoms and /selectors folders separating two files: exampleAtom.ts and exampleSelector.ts. Each of these defines a single atom and a single selector. The /components/Main.tsx file shows how to access the data from both files.

One of the premises of Recoil is to allow better performance by cutting up larger data structures into its component parts, hence the name “atom”. Each atom is subscribed to individually by components that reference it through the hooks useRecoilValue, useRecoilState, and others. So, when these pieces of state update, components attached to them automatically rerender.

This forces us to keep our atoms simple and small, so that multiple components can refer to the just the pieces of data they need, rather than larger data structures that can have changes occur that not all of our components care about, thus forcing our components to rerender when they don’t need to.

How does this relate to our folder structure above? It means that we’re going to have…

--

--

Wesley Rast
Wesley Rast

Written by Wesley Rast

Software Director and Architect

Responses (7)

Write a response