Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Set with react's useState?

Tags:

I have an array that I have to add/remove elements from, and I figured I would use Set to accomplish this because of its add has and delete.

const [tags, setTags] = React.useState(new Set()) 

If I want to add something to tags, how can I do this with setTags? Or do I just call tags.add() ?

like image 303
a person Avatar asked Nov 11 '19 18:11

a person


People also ask

How do you use set in useState?

You can use the hook like const set = useSetState([]) and then call set. add(el) , set. delete(el) etc..

How do you set an array in useState?

Creating an Array state with useState()import React from "react"; const { useState } = React; const [myArray, setMyArray] = useState([]); We destructure the return value of the useState() hook to get a variable that contains the state array and a method for updating the state.

How do you use variables in useState?

When we declare a state variable with useState , it returns a pair — an array with two items. The first item is the current value, and the second is a function that lets us update it. Using [0] and [1] to access them is a bit confusing because they have a specific meaning.

Is set in useState async?

TL;DR: useState is an asynchronous hook and it doesn't change the state immediately, it has to wait for the component to re-render. useRef is a synchronous hook that updates the state immediately and persists its value through the component's lifecycle, but it doesn't trigger a re-render.


1 Answers

A Set is by definition mutable, React won't trigger a new render if you merely call const newSet = set.add(0) cause the shallow comparison between previous and new will always assert to true

You can use the spread operator to change references between each update yet still maintaining all of Set's behaviors

Adding an element

const [state, setState] = useState(new Set())  const addFoo = foo =>{     setState(previousState => new Set([...state, foo])) } 

You could still use the add method since it returns the updated set

const addFoo = foo =>{     setState(prev => new Set(prev.add(foo))) } 

Removing an element

Removing is a little trickier. You first need to turn it into an array, filter and spread the result

const removeFoo = foo =>{     setState(prev => new Set([...prev].filter(x => x !== foo))) } 

For clarity

const removeFoo = foo =>{      setState(prev =>{         return prev.filter(x => x !== foo)     }) } 
like image 184
Dupocas Avatar answered Oct 23 '22 21:10

Dupocas