DEV Community


React state hook , easy way

Heru Hartanto
Frontend developer based in Jakarta
・1 min read

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 
    this.state = {
    render() {
                <p>you hit {this.state.count}</p>
                <button onClick={() => this.setState({ count: this.state.count + 1 })}>
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
            <p> you hit {count} </p>
            <button onClick={()=> setCount(count+1)}>
Enter fullscreen mode Exit fullscreen mode


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

Discussion (1)

freakflames29 profile image
Sourav das

It is helpful :)

Forem Open with the Forem app