2

3 React tips/tricks

 2 years ago
source link: https://medium.com/@rogerfavelron/3-react-tips-tricks-f7e701ef8fea
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Hello. Today I’ll share 3 tips/tricks for React. These are;

1-Do we need to import React for stateless functional components?

2-What is the index.js file in the component directories?

3-Event handlers must always be a function or a reference to a function (with an exception).

So, let’s jump right into it.

1-Do we need to import React for stateless functional components?

Basically, no. In the past, you had to import it but with the new React 17 update , you don’t need to import React .

Further information at : react official blog , stackoverflow

2-What is the index.js file in the component directories?

You may have seen a folder structure like this before :

Why we use index.js here? When we need to import a component, we could’ve done it by directly importing component.

We use index.js, because inside index.js, we can do something like this:

1*qlge-WbZQU5Gu9CQegBIjQ.png?q=20
3-react-tips-tricks-f7e701ef8fea

And when we want to import our components, we can use a syntax like this:

import {CartProduct} from './Components/Cart'

instead of

import {CartProduct} from './Components/Cart/CartProduct'

That’s because when we import a file from a directory, it tries to access index.js file by default . Basically it’s a refactoring technique to keep code simpler.

Further read: stackoverflow

3-Event handlers must always be a function or a reference to a function (with an exception) .

Many people often get confused on about how to use event handlers.

In the below example;

2nd and 3rd buttons won’t work because instead of passing a function or function reference, we’re passing function calls. React calls them on first render, doesn’t wait for buttons to be clicked.

In the 1st example, we are passing a function reference, and in the 4th example, we’re passing a function (literally). Thus , these both work correctly.

But , there’s an exception here. Which are the functions that return functions.

1*00YLTN8L4zvsS4ycUfsr8A.png?q=20
3-react-tips-tricks-f7e701ef8fea

Now, each button has their own handler, this is a cool trick.

If you have any questions/suggestions you can contact me from : [email protected].

And that’s it for today, hope you enjoyed !


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK