Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use arrow functions instead of normal functions for React Hooks?

Tags:

Is it possible to also use arrow functions with the new React Hook syntax? what will be the difference and/or could this cause problems?

documentation syntax:

function Example() {

  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

arrow function:

 const Example = () => {

  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
like image 438
pazta Avatar asked Mar 21 '19 15:03

pazta


People also ask

Should I use arrow function or normal function?

Function expressions are best for object methods. Arrow functions are best for callbacks or methods like map , reduce , or forEach . Use function declarations for functions you'd call by name (because they're hoisted). Use arrow functions for callbacks (because they tend to be terser).

Why we should not use arrow functions in React?

An arrow function doesn't have its own this value and the arguments object. Therefore, you should not use it as an event handler, a method of an object literal, a prototype method, or when you have a function that uses the arguments object.

Can you use arrow functions in React?

Learn more at the React docs. If you use arrow functions within render , each call to render will create new function objects. If you then pass these functions to child elements via props , optimizations based on PureComponent or shouldComponentUpdate will fail (as the arrow function props will change on every render).


2 Answers

The short answer is: yes you can.

Arrow functions and function declarations/expressions are not equivalent. However, if the function you want to replace does not use this, arguments and is not called with new, then you are free to use whatever style you prefer.

like image 118
Michal Avatar answered Sep 26 '22 02:09

Michal


The difference between declaring functional component using function or const would be the same as the difference between functional expressions and functional declaration

For instance Function declarations load before any code is executed while Function expressions load only when the interpreter reaches that line of code i.e rendering a functional component created using function syntax can be done before it is defined in the code while if its defined using expression then it needs to be declared before using

So in short function declarations are hoisted whereas function expressions are not

In terms of using both the above syntaxes to create components you can use either as long as you use hoisting into account

like image 23
Shubham Khatri Avatar answered Sep 25 '22 02:09

Shubham Khatri