1 Minuten Lesezeit

React the easy way, with Hooks

React is already easy, write it with TypeScript and it gets even more easy.

But did you ever notice that most of the code is always the same?

Writing your components in Classes was the way to go until Version 16.8. The Dev Team noticed that most of the code base repeats itself. But why? Where does the overhead come from? The quick answer: Syntax 🤯

With Classes you need to write a lot of code, interfaces, and so on. Think about accessing props. You need to write this.props.title but we don’t want to do that, we want to write just title

Ok, easy, we don’t write a Class, we write a Pure Function. Props problem solved 👍 But what about state, life cycle, etc? 👎


Introducing React Hooks 📌

To get a state one can use the useState() function. This returns an array [property, setProperty] object. Pretty easy. Is it type safe? Yes. Can I put anything I want in useState()? Yes!

Let’s see an example of how this works:

const [isOn, setIsOn] = useState(false);    return (     <div>        the {appliance} is {isOn ? "on" : "off"}        <buttononClick={() =>setIsOn(!isOn)}>power button</button>     </div>  );

Wait what? Where’s the rest?

Let’s do a side by side comparison and see what we have, and we can cut out.


So what’s missing in the second picture?

The Interfaces for the Props and State are no longer needed, the function () => takes care of that. The constructor is no longer needed, the render function is no longer needed. Quite a lot. But still the component can be used like any other:

Let’s see some proof 🔎

Bild von Dan Deaconu
Dan Deaconu Diese Person ist nicht mehr bei der HanseVision tätig. Alle Artikel des Autors

Ähnliche Blog-Artikel

Mit unserem HanseVision Update sind Sie immer gut informiert über alle Themen rund um moderne Zusammenarbeit, kluge Köpfe, Lösungen und Tools, Referenzen und Aktionen.

Jetzt zum Newsletter anmelden
Updates & Aktionen
Versand alle 4-6 Wochen
Trends & aktuelle Entwicklungen