DEV Community

Kazutora Hattori
Kazutora Hattori

Posted on

A simple explanation of the meaning and usage of "prev", "...prev", and "[key]" in React useState

Introduction

When implementing a filter function on a map using React, I found some confusion with the state management mechanism.

I particularly wanted to clearly understand the meaning of the following code,
so I'll briefly explain it in this article.

setFilters(prev => ({
...prev,
[key]: !prev[key]
}));
Enter fullscreen mode Exit fullscreen mode

What is prev?

It stands for "previous."
React automatically passes the current state.

What is ...prev?

In React, it's not allowed to directly manipulate existing data.
So, first "copy the entire previous data"
and then overwrite only the parts of the copy you want to change.

What is [key]: !prev[key]?

[key] is a dynamic key specification.
For example, key = "wifi" means filters.wifi.
!prev[key] inverts the value (true ⇄ false).

When combined, it looks like this:

const toggleFilters = (key) => {
setFilters(prev => ({
...prev,
[key]: !prev[key],
}));
};
Enter fullscreen mode Exit fullscreen mode

You can toggle ON/OFF only the clicked key.

Summary

This code simply copies the previous state and toggles ON/OFF only the specified items.

prev is the previous state,
...prev is its copy,
[key] is the name of the item to update,
!prev[key] inverts its value.

This summarizes the basic patterns for creating toggle and filter functions in React.

Top comments (0)