Wait for state to update when using hooks

The useState hook is asynchronous but it doesn’t have a callback api like setState does. If you want to wait for a state update you need a useEffect hook:

import React, { useState, useEffect } from 'react';

export default function Signup() {
  const [terms, setTerms] = useState('');
  const [termsValidation, setTermsValidation] = useState(false);

  useEffect(() => {
    if (!termsValidation) {
      console.log('run something here');
    }
  }, [termsValidation]);

  function handleSubmit(e) {
    e.preventDefault();

    if (!terms) {
      setTermsValidation(true);
    } else {
      setTermsValidation(false);
    }
  }

  return (
    <div>
      <form>
        <input type="checkbox" id="terms" name="terms" checked={terms} />

        <button type="submit" onClick={handleSubmit}>
          Sign up
        </button>
      </form>
    </div>
  );
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)