DEV Community

Discussion on: React lists without .map

Collapse
 
miketalbot profile image
Mike Talbot ⭐

Well you don't use a .map when you make this list was my point ;)

Good point on the remove - I'd do that by using a useCallback if I'd remembered lol:

function App4() {
    const [render, setRender] = useState(items)
    const remove = useCallback(_remove, [])
    return (
        <Box>
            <List className="App">
                <Repeat list={render}>
                    <RenderItem remove={remove} />
                </Repeat>
            </List>
            <Button variant="contained" color="primary" onClick={add}>
                Add
            </Button>
        </Box>
    )

    function add() {
        setRender((items) => [
            { name: "Made up at " + Date.now(), on: false }
            ...items,
        ])
    }

    function _remove(item) {
        setRender((items) => items.filter((i) => i !== item))
    }
}
Enter fullscreen mode Exit fullscreen mode

The index property is important for many things that require sorting etc and while the component will be called when you update the list it then shouldn't be creating a new element if the index stays stable (as I'm inserting at the top of the list that isn't likely)