Reputation: 482
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
Reputation: 202706
React functions are Javascript functions, with some special rules around them.
React functions:
props
object argumentand 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.
use-
prefixThese 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