Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

183
Visualizações
Using inline arrow function in react functional component

I know it is bad practice to use inline arrow function in react component.

But what should I do when my function has arguments ?

e.g. in CustomInput I have a function to handle focus state and has an argument. I use it in onBlur and onFocus and pass parameter to it.

const CustomInput = () => {
  const [focused, setFocused] = useState(false);

  const handleFocus = (isFocus) => {
    /**
     * Some Conditions to check
     */
    setFocused(isFocus);
  };

  return (
    <input
      onFocus={() => handleFocus(true)}
      onBlur={() => handleFocus(false)}
    />
  );
};
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

It really depends on the standards and conventions your company/project uses. Sometimes, inline arrow-functions are permitted, other times it is a strict rule to define a function, in which case you usually use a handleEvent template.

In the case of a strict rule against inline function declarations, you have several solutions:

  1. Avoid this problem entirely by refraining from Boolean traps.
  2. Rename handleFocus and then create handleFocus and handleBlur functions that call that function.
  3. Use a Reducer that handleFocus and handleBlur will call, each with a different action. (In my opinion, not the best solution for such a small-scale problem)
about 4 years ago · Juan Pablo Isaza Relatório

0

The input focus will either be true or false. You can just pass in the handler function to the listeners, and because you know there will always only be two states, you can simply update the state with the inversion of the current state boolean.

If there are other arguments you think you'll need to pass in I tend to attach the data to data attributes on the element, and then destructure them from the dataset in the handler.

const { useEffect, useState } = React;

function Example() {

  const [focus, setFocus] = useState(false);

  function handleFocus(e) {
    const { text } = e.target.dataset;
    console.log(text);
    setFocus(!focus);
  }

  useEffect(() => {
    console.log(`Focused? ${focus}`);
  }, [focus]);

  return (
    <input
      data-text="This is an example"
      onFocus={handleFocus}
      onBlur={handleFocus}
    />
  );

};

// Render it
ReactDOM.render(
  <Example />,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>

about 4 years ago · Juan Pablo Isaza Relatório

0

I don't know if I correctly understood your question, but here is my take:

It is just about how to pass params and still get handlers to work by returning another function

const CustomInput = () => {
  const [focused, setFocused] = useState(false);

  const handleFocus = (isFocus) => () => {
    /**
     * Some Conditions to check
     */
    setFocused(isFocus);
  };

  return (
    <input
      onFocus={handleFocus(true)}
      onBlur={handleFocus(false)}
    />
  );
};

As for optimisations:

If your component re-renders, your function will be "re-created" either way. Its there you need to decide if optimisation is really needed (no premature optimisations) and if you need it that much it is accomplished by other ways:

  1. extracting function from component
  2. using useCallback (useMemo)
  3. wrapping component in React.memo()

etc...

You can play with an example here: https://codesandbox.io/s/friendly-greider-oph1f?file=/src/App.tsx

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda