React Hooks : useState Array Operations

2nd Feb 2019

React Hooks : useState Array Operations

Here is an example of performing array operations with useState hook.

function ExampleComponent() {
  const [arr, setArr] = React.useState([])

  const addElement = React.useCallback(() => {
    setArr((el) => [
      ...el,
      {
        id: `${Date.now()}`,
        item: el.length,
      },
    ])
  }, [])

  const removeElement = React.useCallback((id) => {
    setArr((prevArr) => prevArr.filter((x) => x.id !== id))
  }, [])

  return (
    <div style={{ display: 'flex', overflow: 'scroll' }}>
      <button onClick={addElement} style={{ margin: 8, padding: 8 }}>
        Add Element
      </button>
      {arr.map((el) => (
        <button
          key={el.id}
          onClick={() => removeElement(el.id)}
          style={{ margin: 8, padding: 8 }}
        >
          Remove {el.item}
        </button>
      ))}
    </div>
  )
}