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)}
/>
);
};
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:
handleFocus
and then create handleFocus
and handleBlur
functions that call that function.handleFocus
and handleBlur
will call, each with a different action. (In my opinion, not the best solution for such a small-scale problem)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>
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:
etc...
You can play with an example here: https://codesandbox.io/s/friendly-greider-oph1f?file=/src/App.tsx