DEV Community

Heru Hartanto
Heru Hartanto

Posted on

1

React state hook , easy way

Hooks are additional in react 16.8, Hooks let us use use state and other React features without writing class wooow 😎

The first "hook" that we will learn is useState, and the other "hook" is useEffect.

useState is similar to declaring state at class component include the setState functionality in one wrap.

Example using class component

class PlusOne extends React.Component{
    // prepare and declaring state 
    constructor(props);
    super(props);
    this.state = {
        count:0
    }
    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

bear in mind that hooks doesn't work with class component

   // import useState from react lib
   import React, { useState } from 'react';
   function PlusOne() {
       const[count,setCount]= useState(0); 
       /* first count variable value set to 0 */
       /* 
        those above line actually is an `array destructuring`
        they are consist of two variable
        count is  current value
        setCount is function that let us update it
       */
       return(
           <div>
            <p> you hit {count} </p>
            <button onClick={()=> setCount(count+1)}>
                +
            </button>
           </div>
       )
   }
Enter fullscreen mode Exit fullscreen mode

Conclusion

  • State hook is similar to declaring state
  • React hook can't use in class components
  • React hook make our components looks more clean

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (1)

Collapse
 
freakflames29 profile image
Sourav das

It is helpful :)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay