Member-only story
Top React Hooks — State History and Validation
3 min readOct 13, 2020
Hooks contains our logic code in our React app.
We can create our own hooks and use hooks provided by other people.
In this article, we’ll look at some useful React hooks.
react-use
The react-use library is a big library with many handy hooks.
useStateValidator
We can use the useStateValidator
hook to validate the state that’s changed in our app.
For instance, we can write:
import React from "react";
import { useStateValidator } from "react-use";const NumberValidator = s => [s === "" || (s * 1) % 2 === 0];export default function App() {
const [state, setState] = React.useState(0);
const [[isValid]] = useStateValidator(state, NumberValidator); return (
<div>
<input
type="number"
min="0"
max="10"
value={state}
onChange={ev => setState(ev.target.value)}
/>
<br />
{isValid !== null && <span>{isValid ? "Valid" : "Invalid"}</span>}
</div>
);
}
to use the useStateValidator
to validate the state.