Coding task · JavaScript and React course · Module 13: Testing React

Practice: Custom Hooks

You cannot call a hook outside a component, so renderHook(() => useToggle()) renders it in a small test component and reads the current value from result.current. When you call toggle twice in one act, the value should come back to the initial one: this only works with an updater function, which receives the latest state. For the same reason, add with an updater function does not lose an item when two items are added quickly.

Task

Finish two custom hooks of the ship cargo hold. useToggle(initialValue) returns [value, toggle], and useList(initialItems) returns { items, add, remove, clear }. ___BLANK1___: toggle switches the value to the opposite one with an updater function (with a current parameter), because toggle is memoized by useCallback and does not see the new value. ___BLANK2___: add appends the item at the end of a new array. ___BLANK3___: remove(index) returns a new array without the item at the given index. Do not change the current array (push, splice): the test freezes the initial array. The test calls the hooks with renderHook and the actions with act, also two in a row in one act.