Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Exercise: custom useArray hook #12

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 34 additions & 1 deletion src/App.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,38 @@
import { useArray } from "./useArray"

const INITIAL_ARRAY = [1, 2, 3]
// const INITIAL_ARRAY = () => [1, 2, 3]

function App() {
return "Hello World"
const { array, set, push, replace, filter, remove, clear, reset } =
useArray(INITIAL_ARRAY)

return (
<>
<div>{array.join(", ")}</div>
<div
style={{
display: "flex",
flexDirection: "column",
gap: ".5rem",
alignItems: "flex-start",
marginTop: "1rem",
}}
>
<button onClick={() => set([4, 5, 6])}>Set to [4, 5, 6]</button>
<button onClick={() => push(4)}>Push 4</button>
<button onClick={() => replace(1, 9)}>
Replace the second element with 9
</button>
<button onClick={() => filter((n) => n < 3)}>
Keep numbers less than 3
</button>
<button onClick={() => remove(1)}>Remove second element</button>
<button onClick={clear}>Clear</button>
<button onClick={reset}>Reset</button>
</div>
</>
)
}

export default App
37 changes: 37 additions & 0 deletions src/useArray.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { useState, useCallback } from "react"

export function useArray(initialValue) {
const [array, setArray] = useState(initialValue)

const push = useCallback((element) => {
setArray((a) => [...a, element])
}, [])

const replace = useCallback((index, newElement) => {
setArray((a) => {
return [...a.slice(0, index), newElement, ...a.slice(index + 1)]
})
}, [])

const filter = useCallback((callback) => {
setArray((a) => {
return a.filter(callback)
})
}, [])

const remove = useCallback((index) => {
setArray((a) => {
return [...a.slice(0, index), ...a.slice(index + 1)]
})
}, [])

const clear = useCallback(() => {
setArray([])
}, [])

const reset = useCallback(() => {
setArray(initialValue)
}, [initialValue])

return { array, set: setArray, push, replace, filter, remove, clear, reset }
}