Manan Bordia
Manan Bordia

Reputation: 482

Difference between Regular javascript functions and React Functions

According to react, we can call hooks from React Functions and not from Regular Javascript functions.

But what is the difference between both of them ?

From this post it seems like there is no difference and it is just different way of writing.

Please provide an example to make the difference more clear.

Upvotes: 6

Views: 4004

Answers (1)

Drew Reese
Drew Reese

Reputation: 202706

React functions are Javascript functions, with some special rules around them.

React functions:

  1. Follow React component naming convention, i.e. they must be Capitalized
  2. Take a single props object argument
  3. Return valid JSX
  4. React functions are NEVER invoked. A reference to them is passed or they are referenced as JSX

and that's about it.

const MyComponent = (props) => <div>{props.greeting}</div>;

Usage:

<MyComponent greeting="Hello World!" />

and never MyComponent({ greeting: "Hello World!" });

This is because the React framework takes this component reference and converts it to a regular old Javascript function and manages calling this function for you. React manages the component lifecycle.

Contrary to the other answer, plain Javascript functions can return JSX. See Rendering Elements. You can assign a JSX literal to a variable, or call a Javascript function that returns a JSX literal.

Example:

const getGreeting = (name) => <div>Hello, {name}!</div>;

const MyComponent = (props) => <div>{getGreeting(props.name)}</div>;

Usage:

<MyComponent name="Drew" /> // --> <div>Hello, Drew!</div>

Similarly, React hooks are also just Javascript functions, but again with special rules applied to them. You can read about these Rules of Hooks.

  1. React hooks follow a naming convention of using a use- prefix
  2. Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions.
  3. Only call Hooks from React function components. Don’t call Hooks from regular JavaScript functions.
  4. Can be called in custom React hooks

These are just rules decided on by the React team to make working with and using React hooks manageable and work within React component lifecycle and keep your sanity.

Upvotes: 14

Related Questions