Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React: StrictMode causing my variable to increment twice

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;

>Solution :

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() }]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading