React useReducer in Strict Mode duplicating result

Strict Mode is triggering my reducer function twice which is expected.

What I didn’t expect was the returned state to have duplicated elements in it.

What I realise is I’m not using useReducer correctly, but I don’t know how to rewrite my reducer function correctly.

The example below should show 1 timestamp on initial render, then with each click of Add Element it should add 1 additional timestamp.
What is happening (with Strict Mode) is each button click is adding 2 additional timestamps.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import { useReducer } from 'react';
const reducer = (state, action) => {
if (action.type === 'addElement') {
let newState = { ...state };
newState.elements.push({
id: (new Date()).toString()
})
return newState;
}
}
export default function Test() {
const [state, dispatch] = useReducer(reducer, {
elements: [
{ id: (new Date()).toString() }
]
});
function addElement() {
dispatch({
type: 'addElement'
});
}
return (
<>
<h2>Elements</h2>
{[...Array(state.elements.length)].map((e, i) => <div key={i}>
<span>{state.elements[i].id}</span><br />
</div>
)}
<button type='button' onClick={addElement}>Add Element</button>
</>
);
}
</code>
<code>import { useReducer } from 'react'; const reducer = (state, action) => { if (action.type === 'addElement') { let newState = { ...state }; newState.elements.push({ id: (new Date()).toString() }) return newState; } } export default function Test() { const [state, dispatch] = useReducer(reducer, { elements: [ { id: (new Date()).toString() } ] }); function addElement() { dispatch({ type: 'addElement' }); } return ( <> <h2>Elements</h2> {[...Array(state.elements.length)].map((e, i) => <div key={i}> <span>{state.elements[i].id}</span><br /> </div> )} <button type='button' onClick={addElement}>Add Element</button> </> ); } </code>
import { useReducer } from 'react';

const reducer = (state, action) => {
  if (action.type === 'addElement') {
    let newState = { ...state };
    newState.elements.push({
        id: (new Date()).toString()
    })
    return newState;
  }
}

export default function Test() {
  const [state, dispatch] = useReducer(reducer, {
    elements: [
        { id: (new Date()).toString() }
    ]
  });

  function addElement() {
    dispatch({
        type: 'addElement'
    });
  }

  return (
    <>
        <h2>Elements</h2>
        {[...Array(state.elements.length)].map((e, i) => <div key={i}>
            <span>{state.elements[i].id}</span><br />
        </div>
        )}
        <button type='button' onClick={addElement}>Add Element</button>
    </>
  );
}

  • You are mutating the original state array directly by using .push() method, even though you spread the rest of the state.
  • Instead of using .push(), spread the existing array into new array & add the new elements using [...state.elements, newElement].
  • Update your reducer function accordingly, here is the code snippet how to do the same.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const reducer = (state, action) => {
if (action.type === 'addElement') {
return {
...state,
elements: [...state.elements, { id: new Date().toString() }]
};
}
return state;
};
</code>
<code>const reducer = (state, action) => { if (action.type === 'addElement') { return { ...state, elements: [...state.elements, { id: new Date().toString() }] }; } return state; }; </code>
const reducer = (state, action) => {
  if (action.type === 'addElement') {
    return {
      ...state,
      elements: [...state.elements, { id: new Date().toString() }]
    };
  }
  return state;
};

From “Strict Mode is triggering my reducer function twice which is expected.” it is obvious from the code that you are pushing twice into the array as an unintentional side-effect.

The React StrictMode component re-runs certain lifecycle methods and hooks twice as a way to help you detect logical issues/bugs in your code.

See Detecting unexpected side effects from the older legacy docs, which do a bit better job of explaining the finer details. I’ve emphasized the relevant point.

Strict mode can’t automatically detect side effects for you, but it
can help you spot them by making them a little more deterministic.
This is done by intentionally double-invoking the following functions:

  • Class component constructor, render, and shouldComponentUpdate methods
  • Class component static getDerivedStateFromProps method
  • Function component bodies
  • State updater functions (the first argument to setState)
  • Functions passed to useState, useMemo, or useReducer

The reducer function is executed twice, and the issue is that you are directly mutating the current state object. In React we never directly mutate state and props. You should update the code to apply the Immutable Update Pattern, i.e. shallow copy all state, and nested state, that is being updated. Array.push directly pushes into the source array and mutates it.

You can use either the Spread Syntax to copy the array, or use Array.concat to append to and return a new array reference.

Examples:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const reducer = (state, action) => {
switch(action.type) {
case 'addElement':
return {
...state, // <-- shallow copy state,
elements: [ // <-- new array reference
...state.elements, // <-- shallow copy array
{ // <-- append new data
id: (new Date()).toString()
}
],
};
default:
return state;
}
}
</code>
<code>const reducer = (state, action) => { switch(action.type) { case 'addElement': return { ...state, // <-- shallow copy state, elements: [ // <-- new array reference ...state.elements, // <-- shallow copy array { // <-- append new data id: (new Date()).toString() } ], }; default: return state; } } </code>
const reducer = (state, action) => {
  switch(action.type) {
    case 'addElement':
      return {
        ...state,            // <-- shallow copy state,
        elements: [          // <-- new array reference
          ...state.elements, // <-- shallow copy array
          {                  // <-- append new data
            id: (new Date()).toString()
          }
        ],
      };

    default:
      return state;
  }
}
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const reducer = (state, action) => {
switch(action.type) {
case 'addElement':
return {
...state, // <-- shallow copy state,
elements: state.elements.concat({ // <-- append new data, return new array
id: (new Date()).toString()
}),
};
default:
return state;
}
}
</code>
<code>const reducer = (state, action) => { switch(action.type) { case 'addElement': return { ...state, // <-- shallow copy state, elements: state.elements.concat({ // <-- append new data, return new array id: (new Date()).toString() }), }; default: return state; } } </code>
const reducer = (state, action) => {
  switch(action.type) {
    case 'addElement':
      return {
        ...state,                         // <-- shallow copy state,
        elements: state.elements.concat({ // <-- append new data, return new array
          id: (new Date()).toString()
        }),
      };

    default:
      return state;
  }
}

Also, just FYI, using dates as GUIDs is not generally recommended. Better to use a library designed for this. Nano ID is a great library for quickly generating sufficiently unique global ID values.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật