We'll use useRef to :
- Automatically focus the input on mount.
- Allow the user to click a "Focus Input" button to manually refocus.
- Autofocuses an input on mount
- Tracks the previous input value
- Shows how many times the input changed without causing re-renders
Example :
import { useRef, useEffect, useState } from 'react';
const TodoAppUseRef = () => {  const inputRef = useRef(null); // Ref for input focus  const prevInputRef = useRef(''); // Ref for previous input value  const [tasks, setTasks] = useState([]);  const [inputValue, setInputValue] = useState('');
  // Auto-focus input on mount  useEffect(() => {    inputRef.current?.focus();  }, []);
  // Update previous input value after each change  useEffect(() => {    prevInputRef.current = inputValue;  }, [inputValue]);
  const handleAddTask = () => {    if (inputValue.trim()) {      setTasks([...tasks, inputValue.trim()]);      setInputValue('');      inputRef.current?.focus(); // Refocus after adding    }  };
  return (    <div style={{ padding: '2rem', fontFamily: 'Arial', maxWidth: 500 }}>      <h2>📝 To-Do List</h2>
      {/* Input with ref and value tracking */}      <input        ref={inputRef}        type="text"        value={inputValue}        placeholder="Enter a task..."        onChange={(e) => setInputValue(e.target.value)}        style={{          padding: '0.5rem',          width: '100%',          marginBottom: '0.5rem',          fontSize: '1rem',        }}      />
      {/* Previous value display */}      <p style={{ fontSize: '0.9rem', color: 'gray' }}>        🔙 Previous Input: <strong>{prevInputRef.current}</strong>      </p>
      {/* Action buttons */}      <div style={{ display: 'flex', gap: '1rem', marginBottom: '1rem' }}>        <button onClick={handleAddTask}>Add Task</button>        <button onClick={() => inputRef.current?.focus()}>🔍 Focus Input</button>      </div>
      {/* Task list */}      <ul>        {tasks.map((task, index) => (          <li key={index} style={{ padding: '0.3rem 0' }}>            ✅ {task}          </li>        ))}      </ul>    </div>  );};
export default TodoAppUseRef;
import { useRef, useEffect, useState } from 'react';
const TodoAppUseRef = () => {
  const inputRef = useRef(null); // Ref for input focus
  const prevInputRef = useRef(''); // Ref for previous input value
  const [tasks, setTasks] = useState([]);
  const [inputValue, setInputValue] = useState('');
  // Auto-focus input on mount
  useEffect(() => {
    inputRef.current?.focus();
  }, []);
  // Update previous input value after each change
  useEffect(() => {
    prevInputRef.current = inputValue;
  }, [inputValue]);
  const handleAddTask = () => {
    if (inputValue.trim()) {
      setTasks([...tasks, inputValue.trim()]);
      setInputValue('');
      inputRef.current?.focus(); // Refocus after adding
    }
  };
  return (
    <div style={{ padding: '2rem', fontFamily: 'Arial', maxWidth: 500 }}>
      <h2>📝 To-Do List</h2>
      {/* Input with ref and value tracking */}
      <input
        ref={inputRef}
        type="text"
        value={inputValue}
        placeholder="Enter a task..."
        onChange={(e) => setInputValue(e.target.value)}
        style={{
          padding: '0.5rem',
          width: '100%',
          marginBottom: '0.5rem',
          fontSize: '1rem',
        }}
      />
      {/* Previous value display */}
      <p style={{ fontSize: '0.9rem', color: 'gray' }}>
        🔙 Previous Input: <strong>{prevInputRef.current}</strong>
      </p>
      {/* Action buttons */}
      <div style={{ display: 'flex', gap: '1rem', marginBottom: '1rem' }}>
        <button onClick={handleAddTask}>Add Task</button>
        <button onClick={() => inputRef.current?.focus()}>🔍 Focus Input</button>
      </div>
      {/* Task list */}
      <ul>
        {tasks.map((task, index) => (
          <li key={index} style={{ padding: '0.3rem 0' }}>
            ✅ {task}
          </li>
        ))}
      </ul>
    </div>
  );
};
export default TodoAppUseRef;
 
 
 
 Posts
Posts
 
 
 
 
 
 
No comments:
Post a Comment