DEV Community

AKSH DESAI
AKSH DESAI

Posted on

react useState() Hook (web dev simplified)

App.js code:

import './App.css';
import { useState } from 'react'

function App() {


  // const [count, setcount] = useState(4);
  // const [count, setcount] = useState(() => {
  //   console.log('only one time render ');
  //   return 4
  // });


  function countInitial() {
    console.log("this will run every time")
    return 4
  }
  const [count, setcount] = useState(countInitial());

  function decrementCount() {
    console.log("decrement");

    // if we write setcount two times that it simply overwrite. it wont works. 
    // setcount(count - 1);
    // setcount(count - 1);

    setcount((prevCount) => {
      console.log('aksh1', prevCount);
      return prevCount - 1
    });

    // setcount((prevCount) => {
    //   console.log('aksh2', prevCount);
    //   return prevCount - 1
    // });
  }


  function incrementCount() {
    setcount(aksh => aksh + 1);
  }
  return (
    <>
      {console.log("re - render")}
      <button onClick={decrementCount}> - </button>
      {count}
      <button onClick={incrementCount}> + </button>
    </>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

another part of app.js code

import './App.css';
import { useState } from 'react'

function App() {


  const [state, setstate] = useState({ count: 4, theme: "blue" });

  function decrementCount() {
    // setstate({count: state.count - 1})

    setstate((prevState) => {
      return {...prevState, count: prevState.count - 1}
    })
  };

  return (
    <>
      <button onClick={decrementCount}> - </button>
      {state.count} - {state.theme}
      <button> + </button>
    </>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Thank You.
You can follow us on:
Youtube
Instagram

Top comments (0)