Non-Visual Behavior (Custom Hooks)
stateful logic
the term stateful logic is not ubiquitous. it just means logic codified (i.e. code) that interacts with state in any way. it can be logic that only reads from the state or logic that updates the state.
in our lesson today, we will be using custom hooks to write code that interacts with state in a reusable way.
simple form project
open the existing project and show how it works for a single username field
what is the
stateful logicin this application?
useForm custom hook
we want to create a hook that will allow us to reuse the stateful logic of dealing with forms. we want to be able to specify different fields and have the hook deal with the updates of the state as things are entered into field.
add a new field
emailby copy/pastingwe can do better. create a
/hooksdirectory and auseForm.jsfile withincopy the
useStatemethods into the form and have the form return the state vars and the update methodsuse
useForminSignupForm.jsbring
clearForminto the hookshow how to create a single
handleChangeswithin the hook for the two fieldsrefactor to make the
useFormuse a customizable initial value object
hooks within hooks
explain that we want to have persistence between page reloads, so we are going to use local storage
open up MDN for localStorage
we will do this by creating a hook that looks and acts like
useStateexcept it save the values locallycreate
useLocalStorage.jsin/hooksflesh it out to mimic the
useStatehook and then call it fromuseFormadd local storage read using an initial value function in
useStateadd local storage setValues by creating it in
useLocalStorage.jsand passing it back as thesetValuesparamthe localStorageSetValues should store the passed in value into the loal storage and then call the useState setValues
Last updated
Was this helpful?