Creating custom hooks
In this section, we’ll learn about custom React hooks. Then, we will use this knowledge to extract the checked logic from the checklist component into a reusable custom hook.
Understanding custom hooks
As well as standard hooks such as useState
, React allows us to create our own custom hooks. Custom hooks allow logic to be isolated and reused across multiple components.
A custom hook is defined using a function with a name that starts with the word use. This naming convention helps ESLint check for problems with the use of the custom hook. Here’s a custom hook that provides toggling logic:
export function useToggle() { const [toggleValue, setToggleValue] = useState(false); function toggle() { setToggleValue(!toggleValue); } return {toggleValue, toggle}; };
The custom hook contains the state of the current toggle value, which is either true
or false
. It also includes...