DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 967,911 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for A little about custom Hooks
Arthur Borges
Arthur Borges

Posted on

A little about custom Hooks

Yeah, I know what you are thinking. But no. React custom Hooks aren't that bad. At least now that I understand them better.

Consider this code for a useState Hook:

const [price, setPrice] = useState(0);

... lots of code here

return (
  <input 
    value={price}
    onChange={(e) => setPrice(e.target.value)}
  />
);
Enter fullscreen mode Exit fullscreen mode

The useState Hook in React is a buit-in hook, which return to you a variable and a function to be used in the code.

One is responsible to set a value (setPrice), and the other one is responsible to retrieve the value (price).

Enter Custom Hooks

From React website, "A custom Hook is a JavaScript function which name starts with ”use” and that may call other Hooks."

So, for this example, let's create a very dumb custom Hook:

const useLuckySeven = () => {
  const random = () => Math.floor(Math.random() * (11 - 1)) + 1;
  if (random !== 10) {
    return 'Too Bad!';
  } else {
    return 'You aced the Lucky Seven!!';
  }
}

export default useLuckySeven;
Enter fullscreen mode Exit fullscreen mode

Then, in another file:

const result = useLuckySeven();
...
<h1>{result}</h1>
Enter fullscreen mode Exit fullscreen mode

Yes, it is that simple! You just extract a function with the "use" keyword prepended to it, and call it elsewhere.

This gonna save a lot of bullets in the future...

Top comments (2)

Collapse
 
pountzas profile image
Nikos

Compact and straight forward thanks a lot Arthur

Collapse
 
arthurborges profile image
Arthur Borges Author

Thank you very much, Nikos!

Classic DEV Post from 2020:

js visualized

πŸš€βš™οΈ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! πŸ₯³

Happy coding!