DEV Community

Cover image for Day 4 of #100DaysOfCode: Scroll event handling and localStorage for React component
Jen-Hsuan Hsieh
Jen-Hsuan Hsieh

Posted on • Edited on

3 1

Day 4 of #100DaysOfCode: Scroll event handling and localStorage for React component

Introduction

Today I just want to add common operations in the React component. What I want to do today is to practice the local storage and the windows event.

Register a scroll event

  • We can register the windows event in useEffect hooks.
const Content = () => {
  const [style, setStyle] = useState('sidebar1')
  React.useEffect( ()=>{
    window.addEventListener('scroll', handleScroll);
    }, []);

  const handleScroll = e => {
    const winScroll =
    document.body.scrollTop || document.documentElement.scrollTop
    if(winScroll < 100) {
        setStyle('sidebar1')
    } else {
        setStyle('sidebar1 sidebar2')
    }
  }

    return (
      <Fragment>
        ...
      </Fragment>
    )
}
Enter fullscreen mode Exit fullscreen mode

Local storage

  • Local storage is one of new features of HTML 5. Users can store data in the browser until delete the local storage manually up to 5 MB. One of the differences between cookie and local storage is that the local storage won't be sent to server-side.
  • The format of key and value are string
const Content = () => {
  const [num, setNum] = useState(0)
  const add = e => {
    setNum(num + 1)
    localStorage.setItem('num', num + 1)
  }
  const remove = e => {
    if (num > 0) {
      setNum(num - 1)
      localStorage.setItem('num', num - 1)
    }
  }
  React.useEffect( ()=>{
    var localNum = localStorage.getItem('num')
    if (localNum !== null) {
      setNum(localNum)
    }else{
      setNum(0)
    }  
  }, []);
    return (
      <Fragment>
        <div className={style}>
          ({num}) Menu
         </div>
        <Menu add={add} remove={remove}/>
      </Fragment>
    )
}
Enter fullscreen mode Exit fullscreen mode

That's it!

Implementations

Articles

There are some of my articles. Feel free to check if you like!

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

👋 Kindness is contagious

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

Okay