rMonteiro
rMonteiro

Reputation: 1666

React Hooks stale state inside function

I have something like this

  const [state, setState] = useState({
    num: 0
  });

  const validateBiggerThan0 = () => {
    return state.num > 0;
  };

  const [validation, setValidation] = useState({
    val: validateBiggerThan0
  });

The problem is when I call validation.validateBiggerThan0, this function does not have the current state. In this simple example, I could pass the value sate.num as a parameter to the validateBiggerThan0, but in my real application this is not feasible because I have multiple validations and some can use more than one value from the state. Is there any alternative to this?

A sandbox with the problem: https://codesandbox.io/s/heuristic-mountain-2poz7?fontsize=14&hidenavigation=1&theme=dark

Upvotes: 0

Views: 1590

Answers (1)

Mat Sz
Mat Sz

Reputation: 2552

The solution to your problem is to not use useState for the function object.

const validation = {
  val: validateBiggerThan0
};

Or to update the object on every change of your state:

useEffect(() => {
  setValidation({
    val: validateBiggerThan0
  });
}, [ state, setValidation, validateBiggerThan0 ]);
// Don't remove "state" from the dependency array.

Don't forget to wrap your validation functions in a useCallback hook in case you use the useEffect method.

const validateBiggerThan0 = useCallback(() => {
  return state.num > 0;
}, [state]);

Upvotes: 2

Related Questions