PROGRAMING/React

[REACT] Score Keeper - localStorage

donghunl 2024. 3. 6. 16:44
반응형

localStorage: localStorage allows you to store data in the browser.

localStorage.getItem(key) // retrieve an item
localStorage.setItem(key, value) // set data in localStorage

 

Display a score that can be increased or decreased.

Use localStorage to store the score so that it persists when you come back to the page.

You should be able to refresh the page and still see the score from the previous render.

 

ScoreKeeper.js

import { useEffect, useState } from 'react'

export default function ScoreKeeper() {
  const [score, setScore] = useState(parseInt(localStorage.getItem('score')) || 0)

  useEffect(() => {
    localStorage.setItem('score', score)
  }, [score])
  return (
    <div>
      <h1>Your score is: {score}</h1>
      <button onClick={() => setScore(prevScore => prevScore + 1)}>+</button>
      <button onClick={() => setScore(prevScore => prevScore - 1)}>-</button>
    </div>
  )
}

 

App.js

import ScoreKeeper from './ScoreKeeper'

function App () {
  return (
    <div className='App'>
      <ScoreKeeper />
    </div>
  )
}

export default App

 

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

 

index.css

html, body {
  font-family: sans-serif;
}

.page {
  height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
}

 

결과 화면

 

반응형

'PROGRAMING > React' 카테고리의 다른 글

[REACT] Color picker  (0) 2024.03.07
[REACT] Window event  (0) 2024.03.07
[REACT] Dog Picture - API  (0) 2024.03.06
[REACT] Form Validator  (0) 2024.03.06
[REACT] Dark mode Light mode toggle  (0) 2024.03.06