What is React Strict Mode?

W
andrewgbliss
9 months ago

In this article we are going to clean up our application and go over React strict mode

. . .

Github repo

https://github.com/EntryLevelDeveloperTraining/todos

Cleaning up an application

Before deploying your application you want to clean up your application. The first thing you want to do is check the console to see if you have any warnings or errors in your React code.

I noticed that when I opened up the console that I was getting this error:

Warning: Each child in a list should have a unique "key" prop.

This is when you are using a map function and dynamically generating a list, like in the list of todos. To fix it we just add a key prop like this:

<List>
  {filteredTodos.map((todo) => {
     return (
       <ListItem key={todo.id}>
         <ListItemText primary={todo.text} />
            <ListItemSecondaryAction>
              <Checkbox
                checked={todo.completed}
                onClick={() => toggleTodo(todo.id)}
              />
              <IconButton onClick={() => removeTodo(todo.id)}>
                <DeleteIcon />
              </IconButton>
            </ListItemSecondaryAction>
          </ListItem>
        );
   })}
</List>

By adding this it says the key will be the id of the todo. Then when it re-renders it knows what the key is.

Adding some padding

Remember to space out your components evenly so it looks good when users use the application. I use the Box component to give padding around some certain elements like this:

<Box pr={1} component="span">
  <Button
    variant="contained"
    color="secondary"
    onClick={() => setFilter("all")}
  >
    All
  </Button>
</Box>

Strict Mode

React strict mode is set in place to give warnings and errors to developers so they can follow the best practices when developing a React application. However, some packages and libraries are falling behind and haven't updated their code to be in compliance with Strict Mode.

So while I was developing this todo application I noticed that sometimes dark mode wouldn't work correctly until I took off Strict Mode.

https://stackoverflow.com/questions/61220424/material-ui-drawer-finddomnode-is-deprecated-in-strictmode

You can read why I took it off on one of the answers here:

Yeah it's annoying. Material UI's team is not keeping up with the React devs. For now, just remove the Strict mode tag. It's unfortunately what happens with cutting edge technologies.


W
andrewgbliss
9 months ago