React Hooks
React Hooks are a new addition in React, it helps us to use state without writing classes.
I.e we can use state in the functional component also.
Rules of Hooks
Hooks are JavaScript functions, but they have two additional rules
-
Top Level
We can only call Hooks at the top level, its cannot be called inside loops, conditions or nested functions.
-
From the component
Don’t call hooks from a regular javascript function.
When do we use Hooks
If we write a function component and we want to use state inside our function component we had to convert it into a class component to be able to use state, but now with the help of hooks we can use state in the function component with converting it into a class component.
Declaring state variable
-
Class Component
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
-
Using Hooks
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
By calling useState we declare our variables, Here “count” is our state variable and setCount is the state.
Using State Hooks
This is an example of useState, This is how a functional component looks like when using hooks.
The Equivalent class component will look something like this
Reading States
When want to display the value of state variable
-
Class
<p>You clicked {this.state.count} times</p>
-
When using Hooks
<p>You clicked {count} times</p>
Updating States
-
Class
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
- When using Hooks
<button onClick={() => setCount(count + 1)}>
Click me
</button>
Conclusion
Hooks have benefited us with the following:
-
How we managing state has become easier to reason about
-
Our code is significantly simplified, and more readable
-
It’s easier to extract and share stateful logic in our apps.
0 Comments:
Leave a Comments