DEV Community

Heru Hartanto
Heru Hartanto

Posted on • Edited on

How to use 'effect' hook easy way

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>
        )
    }
}
Enter fullscreen mode Exit fullscreen mode

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>
       )
   }
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
mohdahmad1 profile image
Mohd Ahmad •

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
Enter fullscreen mode Exit fullscreen mode

```
let x = 100
```
Produces

let x = 100
Enter fullscreen mode Exit fullscreen mode

Notice js after ``` or backticks you prefer

Collapse
 
elukuro profile image
Heru Hartanto •

you're my hero 😊

Collapse
 
lyqht profile image
Estee Tey •

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!