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()
?
You can use the hook like const set = useSetState([]) and then call set. add(el) , set. delete(el) etc..
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.
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.
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.
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) }) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With