Hooks are additional in react 16.8, Hooks let us to use state and other React features without writing class wooow 😎
In previous post I was explained about useState, in this post I will explain about useEffect.
In sort useEffect let us perform side effect after we render component, let see example below.
Example using class component
class PlusOne extends React.Component{
// prepare and declaring state
constructor(props);
super(props);
this.state = {
count:0
}
componentDidMount() {
document.title = `hit ${this.state.count} times`;
}
componentDidUpdate() {
document.title = `hit ${this.state.count} times`;
}
render() {
return(
<div>
<p>you hit {this.state.count}</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
+
</button>
</div>
)
}
}
Example function components using hooks
gently reminder that hooks doesn't work with class component
// import useState and useEffect from react lib
import React, { useState,useEffect } from 'react';
function PlusOne() {
const[count,setCount]= useState(0); /* first count variable value set to 0 */
useEffect(()=>{
/*
use effect let us express side effect after component rendered.
*/
document.title = `hit ${count} times`;
},[count]) // only re-run effect if count changes
return(
<div>
<p> you hit {count} </p>
<button onClick={()=> setCount(count+1)}>
+
</button>
</div>
)
}
Top comments (3)
Please add syntax highlighting, it will be easy to read.
do it by adding js(or any other programming language name) after backticks(```)
```js
let x = 100
```
Produces
```
let x = 100
```
Produces
Notice js after ``` or backticks you prefer
you're my hero 😊
I think it may be better if you include your explanation as markdown text outside of the code blocks, rather than comments in the code itself. I would love to see more explanation and your perspective of why you prefer writing hooks over class components!