Categories
React Hooks

Top React Hooks — State History and Validation

Spread the love

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.

We pass in the state as the first argument.

The 2nd is the NumberValidator to validate our state.

It takes the state and returns an array that has the validation state of the state .

It returns an array that’s nested in an array with the validation state.

Then we can use that anywhere we like.

useStateHistory

The useStateHistory hook lets us store a set amount of previous state values and provides handles to travel through them.

To use it, we can write:

import React from "react";
import { useStateWithHistory } from "react-use";

export default function App() {
  const [state, setState, stateHistory] = useStateWithHistory(2, 10, [1]);

  return (
    <div>
      <button onClick={() => setState(state + 1)}>increment</button>
      <p>{JSON.stringify(stateHistory, null, 2)}</p>
      <p>{JSON.stringify(state)}</p>
    </div>
  );
}

We use the useStateWithHistory hook with a few arguments.

The first argument is the initial state.

The 2nd argument is the maximum number of items to keep.

The 3rd is the initial history.

It returns an array with the state which has the state value.

setState lets us update the state.

stateHistory has the state history.

It’s an object with various methods.

The position has the position in history.

capacity has the max capacity of the history list.

back lets us move backward in the state history.

forward lets us move forward in the state history.

go lets us go to an arbitrary position in the state history.

useMultiStateValidator

The useMultiStateValidator hook lets us invoke a validator function if any state changes.

For instance, we can write:

import React from "react";
import { useMultiStateValidator } from "react-use";

const NumberValidator = s => [s.every(num => num % 2 === 0)];

export default function App() {
  const [state1, setState1] = React.useState(1);
  const [state2, setState2] = React.useState(1);
  const [state3, setState3] = React.useState(1);
  const [[isValid]] = useMultiStateValidator(
    [state1, state2, state3],
    NumberValidator
  );

  return (
    <div>
      <input
        type="number"
        min="1"
        max="10"
        value={state1}
        onChange={ev => {
          setState1(ev.target.value);
        }}
      />
      <input
        type="number"
        min="1"
        max="10"
        value={state2}
        onChange={ev => {
          setState2(ev.target.value);
        }}
      />
      <input
        type="number"
        min="1"
        max="10"
        value={state3}
        onChange={ev => {
          setState3(ev.target.value);
        }}
      />
      {isValid !== null && <span>{isValid ? "Valid" : "Invalid"}</span>}
    </div>
  );
}

We have 3 states, which we can set with their own input box.

And we call useMultiStateValidator with the numbers and the NumberValidator to validate the numbers.

NumberValidator takes has an array with the array we passed in as the argument.

And it returns an array with the validation condition of all the entries.

It returns a nested array with the validation state of all the numbers.

It’ll only return true if all of them meet the criteria in the callback for every as we specified.

Conclusion

The react-use library lets us validate states and list the past values of a state in an array.

Leave a Reply

Your email address will not be published. Required fields are marked *