Snippets Collections
import { useState, useEffect, useRef } from "react";
export default function App() {
  const [day, setDay] = useState("Monday");
  const prevDay = usePrevious(day);
  const getNextDay = () => {
    if (day === "Monday") {
      setDay("Tuesday")
    } else if (day === "Tuesday") {
      setDay("Wednesday")
    } else if (day === "Wednesday") {
      setDay("Thursday")
    } else if (day === "Thursday") {
      setDay("Friday")
    } else if (day === "Friday") {
      setDay("Monday")
    }
  }
  return (
    <div style={{padding: "40px"}}>
      <h1>
        Today is: {day}<br />
        {
          prevDay && (
            <span>Previous work day was: {prevDay}</span>
          )
        }
      </h1>
      <button onClick={getNextDay}>
        Get next day
      </button>
    </div>
  );
}
function usePrevious(val) {
  const ref = useRef()

  useEffect(() => {
    ref.current = val
  }, [val])
  return ref.current
}
import { useState, useEffect } from "react";

function getValue(key, initailValue) {
  const storedValue = JSON.parse(localStorage.getItem(key));
  if (storedValue) return storedValue;

  if (initailValue instanceof Function) return initailValue();
  return initailValue;
}

export default function useLocalStorage(key, initailValue) {
  const [value, setValue] = useState(() => {
    return getValue(key, initailValue);
  });

  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [value]);

  return [value, setValue];
}
star

Wed Dec 28 2022 09:32:11 GMT+0000 (Coordinated Universal Time) https://www.coursera.org/learn/advanced-react/supplement/DcqzI/solution-create-your-own-custom-hook-useprevious

#react.js #useref #ref #hooks #customhook
star

Sun Jul 24 2022 20:33:08 GMT+0000 (Coordinated Universal Time)

#react #localstorage #customhook

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension