Home > Blockchain >  React: StrictMode causing my variable to increment twice
React: StrictMode causing my variable to increment twice

Time:07-04

I am new to React development and at loss with StrictMode functionality that would invoke/re-render the component twice.

For example, I did some Todo App and want to increment my globalID variable everytime user clicked Create Todo button. In StrictMode, my component re-rendered twice which also increment my globalID twice.

REAL QUESTION: Is there any workaround for this code? I don't want to remove StrictMode because it will help me detect bugs in future, and at the same time I don't want StrictMode to give me false information as in this case.

Without StrictMode With StrictMode

Code Sample

import React, { useState } from 'react';
import './App.css';

let globalID = 0;

function App() {
    const [task, setTask] = useState('');
    const [todos, setTodos] = useState([]);

    function createTodo(event) {
        event.preventDefault();

        setTodos(oldTodos => [...oldTodos, { todo: task, id: globalID   }]);
        setTask('');
    }

    function deleteItem(itemID) {
        // TODO: filling this up soon
    }

    return (
        <div>
            <form onSubmit={createTodo}>
                <h1>Best To Do App Ever</h1>
                <input
                    type="text"
                    value={task}
                    onChange={(event) => {
                        setTask(event.target.value);
                    }}
                />
                <button>Create Todo</button>
            </form>

            <ul>
                {todos.map((item) => {
                    return (
                        <div key={item.id}>
                        <li>
                            {item.todo} ({item.id})
                        </li>
                        <button onClick={() => deleteItem(item.id)}>
                            Delete
                        </button>
                    </div>
                    );
                })}
            </ul>
        </div>
    );
}

export default App;

CodePudding user response:

Instead of a mutable integer which starts at 0 and that you increment for each generation, use a UUID: Crypto.randomUUID(). This will also allow you to solve a potential future issue (where the ID pool resets every time the app reloads).

// Before
setTodos(oldTodos => [...oldTodos, { todo: task, id: globalID   }]);

// After
setTodos(oldTodos => [...oldTodos, { todo: task, id: window.crypto.randomUUID() }]);
  • Related