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.
CodePudding user response:
React Functions
React functions are actually Functional Components that returns some amount of JSX (templating syntax for react). You can also use hooks in Functional Components. Functional Components are the combinations of Logic UI. For example you want to create a Header for website you will create Functional Component for that to show some UI and perform some logic.
Regular Functions
While on the other hand Regular functions are just normal JavaScript functions to perform some action. Let's say you will create a function that transform lowercase letters to uppercase letters. It can not return JSX.
CodePudding user response:
React functions are Javascript functions, with some special rules around them.
React functions:
- Follow React component naming convention, i.e. they must be Capitalized
- Take a single
propsobject argument - Return valid JSX
- 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.
- React hooks follow a naming convention of using a
use-prefix - Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions.
- Only call Hooks from React function components. Don’t call Hooks from regular JavaScript functions.
- 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.
