1

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)}
    />
  );
};
8
  • "I know it is bad practice to use inline arrow function in react component." -> who said that? Commented Sep 19, 2021 at 8:36
  • @giorgimoniava refer to stackoverflow.com/questions/36677733/… Commented Sep 19, 2021 at 9:48
  • that is an old question and doesn't apply to hooks. Besides performance is mentioned which in most of the cases won't be noticeable Commented Sep 19, 2021 at 9:49
  • @giorgimoniava So you are saying it may cause some small performance issues. By accept this, how can improve it? Commented Sep 19, 2021 at 9:51
  • Honestly, I don't understand what your problem is Commented Sep 19, 2021 at 9:52

4 Answers 4

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

For solution #1 that you mentioned, how would refactor the onFocus and onBlur props? Define separate setFocused and setBlurred functions that take no arguments and just set the focused state to true or false within the implementation respectively?
No, the second you click (or tab) inside/outside of the element it triggers
1

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>

9 Comments

That was just an example, think argument accept many values.
why use data attribute when you can just use as callback (e)=>handleFocus(e,"This is an example")?
I find data attributes more expressive and readable.
Fine, also his point about arrow functions confuses me, even official react docs start with arrow function in example:reactjs.org/docs/hooks-intro.html
This is a very situation-specific answer, I think OP intended to receive a bit broader solution.
|
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

Comments

-2

use the function after binding this to null like:

<input
      onFocus={handleFocus.bind(null,true)}
      onBlur={handleFocus.bind(null,false)}
/>

1 Comment

How is that at all helpful?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.