In this blog, we will learn about useState and useEffeact in react hooks. Hooks are a new edition in React 16.8. React hooks provide an ability to use state and lifecycle functions within functional components.
Before knowing about the two major hooks(i.e useState and useEffect) we need to keep some major rules regarding hooks in our mind.
- Don’t call hooks from inside nested functions, loops, or conditionals.
- Don’t call hooks from a regular JavaScript function.
useState
The useState hook is a function that takes one argument, which is the initial state, and it returns two values: the current state and a function that can be used to update the state.
let's see an example
import React, { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
useState is a new way to use the exact same capabilities that this.state provides in a class.
square brackets("[]") is a JavaScript syntax called "array destructing". It is used for It means that we’re making two new variables "count" and "setCount".
The only argument to the useState is the initial state. So in the above example, "0" is the initial state for the variable count.
useState returns an array of two values the current state value and the function/method that can be used to update the state. So in the above example, it returns two values count and setCount.
useEffect
useEffect Hook is to eliminate the side-effects of using class-based components. This hook is the ideal place to set up listeners, fetching data from API and removing listeners before the component is removed from the DOM.
The useEffect hook is the combination of componentDidMount(run only once when the component is inserted into the DOM tree structure) componentDidUpdate(run something on each render), and componentWillUnmount (run when the component will be removed from the DOM tree) class lifecycle methods.
let's see an example
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
useEffect placing inside the component lets us access the count state variable (or any props) right from the effect.
useEffect runs both after the first render and after every update.
useEffect doesn’t block the browser from updating the screen.
Conclusion
So, we can say that hooks are added to React to use "state" within the functionals components instead of using classes.
Hopefully, useState and useEffect is a bit clear by now. If any queries regarding this write them down below. Thank you for your time and I hoped my blog is helpful for you.
Happy Learning!!
Top comments (1)
what are advantages of both on other?