useLocalStorage Hook

useLocalStorage Hook

Hard ReactJS Hooks & Effects 25 views
Explanation Complexity

Problem Statement

Create a useLocalStorage hook and use it for a text setting.

Input Format

No input.

Output Format

Render a React component.

Constraints

Read in initializer and write on change with try/catch.

Input / Output Format

Input Format
No input.
Output Format
Render a React component.
Constraints
Read in initializer and write on change with try/catch.

Examples

Input:
Output:
(React code)

Example Solution (Public)

ReactJS
import React, { useEffect, useState } from 'react';

function useLocalStorage(key, initialValue) {
  const [value, setValue] = useState(() => {
    try {
      const raw = localStorage.getItem(key);
      if (raw == null) return initialValue;
      return raw;
    } catch {
      return initialValue;
    }
  });

  useEffect(() => {
    try {
      localStorage.setItem(key, String(value));
    } catch {}
  }, [key, value]);

  return [value, setValue];
}

export default function App() {
  const [name, setName] = useLocalStorage('meetcode_name', '');

  return (
    <div style={{ padding: 16, width: 520 }}>
      <h2 style={{ marginTop: 0 }}>meetcode greeting</h2>
      <input value={name} onChange={(e) => setName(e.target.value)} placeholder='Your name' style={{ width: '100%', padding: '10px 12px', borderRadius: 12, border: '1px solid #bbb' }} />
      <div style={{ marginTop: 10, color: '#555' }}>{name ? 'Hello ' + name : 'Type your name'}</div>
    </div>
  );
}

Official Solution Code

import React, { useEffect, useState } from 'react';

function useLocalStorage(key, initialValue) {
  const [value, setValue] = useState(() => {
    try {
      const raw = localStorage.getItem(key);
      if (raw == null) return initialValue;
      return raw;
    } catch {
      return initialValue;
    }
  });

  useEffect(() => {
    try {
      localStorage.setItem(key, String(value));
    } catch {}
  }, [key, value]);

  return [value, setValue];
}

export default function App() {
  const [name, setName] = useLocalStorage('meetcode_name', '');

  return (
    <div style={{ padding: 16, width: 520 }}>
      <h2 style={{ marginTop: 0 }}>meetcode greeting</h2>
      <input value={name} onChange={(e) => setName(e.target.value)} placeholder='Your name' style={{ width: '100%', padding: '10px 12px', borderRadius: 12, border: '1px solid #bbb' }} />
      <div style={{ marginTop: 10, color: '#555' }}>{name ? 'Hello ' + name : 'Type your name'}</div>
    </div>
  );
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.