React Hooks for beginners

The new way to write components

What are Hooks?

Hooks let you use state and other React features to achieve the same result in a functional component, without writing a class.

Some benefits are that writing functions instead of classes can have a great impact on performance and readability of the code. Plus, you don't need to reference the ‘this’ key word all over the place.

React hook rules

  • You should call them at the top of your react function. This is important because it allows React to call it in the same order every render.
  • You cannot call Hooks from regular vanilla JavaScript functions. You must always use a react function.

How to use react hooks

useState(): A typical class component would use State as follows.

Class Component

The state is defined within the constructor and set a default value of ‘count’ to 0. This code snippet shows that every time we click on the button, we add 1 to the value ‘count’.

The same thing can be achieved with a functional component :

Functional Component

You can already see that the code is much more condensed and is easier to read.

The main differences are:

  • useState() is imported from React (line 1)
  • The hook is called at the top of the function.
  • The hook takes one optional argument, which is the default state, which has been set to ‘0’. Unlike classes, the ‘state’ here doesn’t have to be an object. We can call as many useState as we like.
  • The function then returns an array that contains two values you can use within your component:
 const [count, setCount] = useState(0)
  • The reason they are returned in an array is because we can de-structure them with JavaScript to easily assign the values to local variables that we can name what ever we want.
  • One more difference is that the class uses this.setState and then this.state.count when we can to access the value, where as in the functional component we can set up a new value using the function setCount and add 1 to the current count value (line 9).

Conclusion

They coexist with existing class components and they’ll still be supported in the foreseeable future.

Hooks remove the confusion that arises from JavaScript classes and also let React minify the code by providing additional optimizations that can’t be done with classes.

Sources:

https://reactjs.org/docs/hooks-overview.html
https://reactjs.org/docs/hooks-rules.html
https://reactjs.org/docs/hooks-state.html
https://reactjs.org/docs/hooks-effect.html

Computer science graduate 2021. 1 year technology placement in investment banking. Full stack:ReactJS, JavaScript, NodeJS,Flask,SQL, AWS Crypto enthusiast