Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

128
Vistas
React 2 ouside events cannot share hook data

I have 2 outside events, input and keydown for an input element, when input fired, it will call setInput in React component. When keydown event for arrowDown fired, ideally the input value should be the one set inside handleInput, but it's empty, do I miss something?

const SearchBox : React.FunctionComponent<ISearchProps> = React.memo((props: ISearchProps) => {
   const [input, setInput] = React.useState({value: '', redirect: false});

    useEffect(() => {
        const container = document.querySelector('.xxx');
        container.addEventListener('input', handleInput);
        container.addEventListener('keydown', handleKeyboardEvent);
    }, []);

    const handleInput = (e) => {
        setInput({value: e.currentTarget.value, redirect: false});
    }

    const handleKeyboardEvent = (e) => {
        switch (e.key) {
            case 'ArrowDown':
                console.log(input);
                setActiveSuggestionIndex(activeSuggestionIndex === suggestions.length - 1 ? 0 : activeSuggestionIndex + 1);
                e.preventDefault();
                break;
            default:
                break;
        }
    }
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Issue

This is an issue of stale enclosures of state in a callback function. The initial input state value of { value: '', redirect: false } is closed over in the copy of handleKeyboardEvent from the initial render cycle. It will never update.

Solutions

Use React ref and useEffect to cache a copy of value

Use a React ref and an additional useEffect hook to cache a value to be accessed asynchronously in the callback.

const [input, setInput] = React.useState({ value: '', redirect: false });
const inputRef = React.useRef(input); // <-- state cache

useEffect(() => {
  const container = document.querySelector('.xxx');
  container.addEventListener('input', handleInput);
  container.addEventListener('keydown', handleKeyboardEvent);

  return () => {
    container.removeEventListener('input', handleInput);
    container.removeEventListener('keydown', handleKeyboardEvent);
  };
}, []);

useEffect(() => {
  inputRef.current = input; // <-- update state cache value
}, [input]);

const handleInput = (e) => {
  setInput({ value: e.currentTarget.value, redirect: false });
};

const handleKeyboardEvent = (e) => {
  switch (e.key) {
    case 'ArrowDown':
      console.log(inputRef); // <-- read current state cache value

      setActiveSuggestionIndex(activeSuggestionIndex => 
        activeSuggestionIndex === suggestions.length - 1
          ? 0
          : activeSuggestionIndex + 1
      );
      e.preventDefault();
      break;
    default:
      break;
  }
};

Use useEffect with dependency and cleanup function

Since you should also already be returning a cleanup function from the useEffect to remove the event listeners when unmounting, add the input state to the dependency array (and any other missing dependencies the linter may complain about) so that when the input state updates, the current state value is re-enclosed in callback scope.

useEffect(() => {
  const handleInput = (e) => {
    setInput({ value: e.currentTarget.value, redirect: false });
  };

  const handleKeyboardEvent = (e) => {
    switch (e.key) {
      case 'ArrowDown':
        console.log(input);

        setActiveSuggestionIndex(activeSuggestionIndex => 
          activeSuggestionIndex === suggestions.length - 1
            ? 0
            : activeSuggestionIndex + 1
        );
        e.preventDefault();
        break;
      default:
        break;
    }
  };

  const container = document.querySelector('.xxx');

  container.addEventListener('input', handleInput);
  container.addEventListener('keydown', handleKeyboardEvent);

  return () => {
    container.removeEventListener('input', handleInput);
    container.removeEventListener('keydown', handleKeyboardEvent);
  };
}, [input]);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda