Back to blog overview

June 9, 2023

How to Use RedwoodJS Cells

Natalia Diaz

&

&

Software Engineer
Chula Vista, CA

## What are Cells in RedwoodJS?

Have you worked in a full-stack application and gotten confused about how to fetch necessary data? Have you had a component cluttered with data fetching, HTML elements, and styles all in the same component?

[RedwoodJS](https://redwoodjs.com/) is a full-stack framework that has introduced features and structure to make building out your application straightforward. Since RedwoodJS is full stack, your application has a web and an API side, making it a [monolith project](https://www.techtarget.com/whatis/definition/monolithic-architecture). In this blog, we will focus on the web side. RedwoodJS has structured the web side for components, layouts, pages, and routes. Within the components directory are Cells, which are components designed to fetch your data from the API side and accessible to use on the web side.  

## Why Use RedwoodJS Cells?

You may be thinking, do I really need to add cells to my project? Well, using cells throughout your application helps developers work through data fetching and reduce code duplication. RedwoodJS cells ease the web development process, fetching information in its own component.

### Simplify Data Fetching

When a Cell is invoked, it initiates a data-fetching operation that retrieves the required data from the database. Once the data has been fetched, it is passed on to the Cell's render function, which then generates the UI. This process starts with a query like the following:

```markdown
export const QUERY = gql`
 query FindUsers {
   users {
     id
     email
     name
   }
 }
`
```

Then within the cell, if the data is present, loading, or empty there are constants to account for those cases. The following are some examples of cases that can be rendered if the value matches:

```markdown
export const Loading = () => <div>Loading...</div>

export const Empty = () => {
 return (
   <div className="rw-text-center">
     {'No users yet. '}
     <Link to={routes.newUser()} className="rw-link">
       {'Create one?'}
     </Link>
   </div>
 )
}

export const Failure = ({ error }: CellFailureProps) => (
 <div className="rw-cell-error">{error?.message}</div>
)

export const Success = ({ users }: CellSuccessProps<FindUsers>) => {
 return <Users users={users} />
}
```

Within this component users’ data are easily returned within a few lines. This is a basic data fetch but has the capacity to allow more complex data fetching if required. Cells are designed to optimize data fetching by minimizing the amount of data transferred between the server and the client. The exact data requested is the exact data retrieved.  

### Efficient Code Base

Cells encourage developers to separate data fetching logic from UI code, making it easier to manage and maintain your application over time. Cells can be reused across multiple components, reducing the amount of code duplication in your application. This cell space goes between the request and the response, making necessary query changes without changing any backend code. Cells are a way for your application to use your queries, and fetch data from the database. This data fetching is kept in the cell, its own component making it easier to test separate from UI code.

## Adding Cells to Your Project

The first step in starting your project is setting up the [schema](https://www.prisma.io/docs/concepts/components/prisma-schema) and graphql files. The schema file is designed to create your model table, noting the model’s fields and data types. The GraphQL file is where to set up queries for your models. If you’d like more information about your GraphQL setup, [click here for more information](https://www.codingzeal.com/post/how-to-use-graphql-in-redwoodjs).

After your schema is compiled and a migration of your new table is sent to the database, RedwoodJS has a useful command that helps to set up the build process for actions on the API and web sides. Use the following command:

```markdown
yarn rw g scaffold user
```

This command has scaffolded out files related to the model User. Below is a list of files created from just one command!

From that one command, API and web files involving the User are made to go through [CRUD](https://www.notion.so/ZEAL-Glossary-090ff70c3adc4b57933b33fcb6e113b8?pvs=21) actions. We’ll focus on the cell files that were created. There is a cell made for:

- EditUserCell
- UserCell
- UsersCell

These generated cells have correlating components to house the UI to render all the data fetched. The cells will take care of all the query and brain power, so the component will hold the layout and styling. This also helps in testing the cell and component separately to ensure the correct information is being queried, and the information is being displayed or used correctly.

This is just one way to create a cell. To create one cell at a time use the following command:

```markdown
yarn rw generate cell user
```

This command will create four files.

```markdown
~/redwood-app$ yarn rw generate cell user
 ✔ Generating cell files...
   ✔ Writing `./web/src/components/UserCell/UserCell.mock.js`...
   ✔ Writing `./web/src/components/UserCell/UserCell.stories.js`...
   ✔ Writing `./web/src/components/UserCell/UserCell.test.js`...
   ✔ Writing `./web/src/components/UserCell/UserCell.js`...
```

In RedwoodJS, you’re able to have a single item cell or a list cell. RedwoodJS is intuitive to identify singular from plural. If there is a pluralization with an irregular word where the singular and plural are the same, there is a flag to add to the command to ensure you meant the list cell to be generated. The following command includes the flag to signify the listed cell:

```markdown
yarn rw generate cell equipment --list
```

This command will create the same four files as the previous command for a model of equipment.

The benefit of generating a cell with these commands is the additional files generated along with the main cell component. The command preps you with a test file, stories file, and mocks file. With the scaffold command, simply the cell component is generated.

## How to Use Cells in RedwoodJS

When your cell is generated there are a few file exports that are automatically added in the component. Cells execute a GraphQL query and manage its lifecycle, grabbing all information necessary for that particular component.

The necessary actions for a cell are Query and Success. Additonal actions are beforeQuery, isEmpty, afterQuery, Loading, Empty, and Failure. These other actions help to organize your data and complete an action when met.

Here is an example of a cell focused on fetching data on a specific user with a few of the actions previously mentioned:

```markdown
import type { FindUserById } from 'types/graphql'
import type { CellSuccessProps, CellFailureProps } from '@redwoodjs/web'
import User from 'src/components/User/User'

export const QUERY = gql`
 query FindUserById($id: Int!) {
   user: user(id: $id) {
     id
     email
     name
   }
 }
`

export const Loading = () => <div>Loading...</div>

export const Empty = () => <div>User not found</div>

export const Failure = ({ error }: CellFailureProps) => (
 <div className="rw-cell-error">{error?.message}</div>
)

export const Success = ({ user }: CellSuccessProps<FindUserById>) => {
 return <User user={user} />
}
```

Working through this query, if the User model had an association that referred to another model it is possible to query in your cell in the same instance. For example, if the user had a value of books saved, it would refer to the Book model. The query can then include elements of the Book model table within this user query.

Connecting that association will look like the following:

```markdown
export const QUERY = gql`
 query FindUserById($id: Int!) {
   user: user(id: $id) {
     id
     email
     name
books {
author
title
   }
   }
 }
`
```

Now this cell can fetch the user’s information and the user’s book information. Cells are able to grab this data and connection easily, making the build process simplified and quick.

## In Conclusion

Hopefully, reading through has improved your understanding and you see the benefits of using cells in your project. Cells separate the logic from your styled component, simplify data fetching, and are reusable throughout your application. Your code base becomes organized and easy to test. You can be extensive in data fetching, and easily navigate data associations.

Now that your logic and data fetching are set up it's time to organize and style your correlating component. If you are thinking of incorporating Tailwind into your application to simplify and standardize styling, check out [Tailwind information here](https://www.codingzeal.com/post/tailwind-is-a-popular-library-here-is-how-to-add-it-to-redwoodjs). Happy developing!

Photo by Mick Haupt on Unsplash

Let's Chat

Are you ready to build something brilliant? We're ready to help.

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
RedwoodJS Logo
RedwoodJS
Conference

conference
for builders

Grants Pass, Oregon • September 26 - 29, 2023
View All