Created
April 8, 2020 22:22
-
-
Save ipetropolsky/24218076ec29dad8e580f5620deff23c to your computer and use it in GitHub Desktop.
useUniqueArray hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useCallback, useState } from 'react'; | |
/** | |
* Хук для хранения уникального набора элементов в массиве. | |
* Возвращает массив и функцию переключения элемента. | |
*/ | |
export default (initialValue = []) => { | |
const [items, setItems] = useState(initialValue); | |
const toggle = useCallback( | |
(item, force = null) => { | |
const hasItem = items.includes(item); | |
if (hasItem && (force === false || force === null)) { | |
setItems(items.filter((value) => value !== item)); | |
} else if (!hasItem && (force === true || force === null)) { | |
setItems([...items, item]); | |
} | |
}, | |
[items] | |
); | |
return [items, toggle]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment