Skip to content

Instantly share code, notes, and snippets.

@Bwogi
Last active December 11, 2021 12:52
Show Gist options
  • Select an option

  • Save Bwogi/09772e2eb158c4336d3da1ea1fa34352 to your computer and use it in GitHub Desktop.

Select an option

Save Bwogi/09772e2eb158c4336d3da1ea1fa34352 to your computer and use it in GitHub Desktop.
State management explained in React

useState explained

Isn't this beautiful?(/components/Counter/index.js)

import { useState } from 'react';
const Counter = ({ max }) => {
	const [count, setCount] = useState(0);
	return (
		<div>
			<h1>Walmart Guests: {count}</h1>
			<h3>out of: {max}</h3>
			<button
				className='btn'
				onClick={() => {
					if (count < max) setCount(count + 1);
				}}>
				New Guest(+)
			</button>
			<button
				className='btn'
				onClick={() => {
					if (count > 0) {
						setCount(count - 1);
					}
				}}>
				Guest Left(-)
			</button>
		</div>
	);
};

export default Counter;

See how Counter is propped(with max)? (App.js)

import React from 'react';
import Counter from './components/Counter';
import './App.css';

const App = () => {
	return (
		<div className='container'>
			<Counter max={5} />
		</div>
	);
};

export default App;

this will not work in Reactjs

import React from "react"

function SomeComponent() {
let seconds = 0

function startStopwatch() {
  setInterval(() => {
    console.log(seconds)
    seconds += 1
  }, 1000)
}

return (
  <div>
    {seconds}
    <button onClick={startStopwatch} >Start</button>
  </div>
)
}

In vanilla javascript the above statement works perfectly fine but in Reactjs it wont.

try this instead

import React {useState} from 'react'

const ClickCounter = () => {
  const [count, setCount] = useState(0)

  const increment = () => {
    setCount((prevState) => prevState + 1)
  }
  return (
    <div>
      <p>I have been clicked {count} times.</p>
      <button onClick={increment}>Add One</button>
    </div>
  )
}

export default ClickCounter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment