REACTJS learning here, I have very weird issue in REACTJS, when strictmode is disable my code is working but when strictmode is on my code is not working. Any help would be greatly appreaciate. Thankyou! link to codesandbox = https://codesandbox.io/s/toggle-problem-6kr0b?file=/src/index.js I wonder why strictmode would cause such impact to my code. Thank you in advance!
(App)
//------------------------------------------
import { StrictMode } from "react";
import ReactDOM from "react-dom";
import Todo from './Hi'
import App from "./App";
const rootElement = document.getElementById("root");
ReactDOM.render(
<div>
<App />
</div>,
rootElement
);
//--------------------------------------------------------------------------------------
import React, { useReducer } from "react";
function Texting() {
const state = {
list: [{ name: "i am nice", style: { color: "blue" } }]
};
const [listt, dispatch] = useReducer(reducer, state);
function reducer(listt, action) {
switch (action) {
case "toggle":
console.log("hi");
const clone = [...listt.list];
if (clone[0].style.color === "blue") {
clone[0].style = { color: "red" };
return { ...listt, list: clone };
} else {
clone[0].style = { color: "blue" };
return { ...listt, list: clone };
}
}
}
return (
<div>
<fieldset>
<legend>Clone with object</legend>
<button
onClick={() => {
dispatch("toggle");
}}
>
Click me to toggle color!
</button>
<h2 style={listt.list[0].style}>Me</h2>
{listt.list[0].style.color}
</fieldset>
</div>
// <div>
// Color = {listt.list.map((x) => x.style.color)}
// <button onClick={() => dispatch("toggle")}>toggle!</button>
// <h2 style={listt.list[0].style}>
// I am awesome
// </h2>
// </div>
);
}
export default Texting;
I haven't looked at your code. But from my understanding, the component will render twice in strict mode instead of just once for every change in state or input props. Maybe that is the reason.
One more thing, you should place the reducer function outside the componennt so it won't get created on every render. Should work as you have it right now, but for performance sake it's better to define it outside of the component.
In strict mode you must fix warnings also. In switch you forgot default. Check this link: https://codesandbox.io/s/toggle-problem-forked-hkijk
StrictMode is used to know potential problems at the time of development.
The problem with your code is that you have missed default case in switch statement.
Try following :
switch (action) {
case "toggle":
console.log("hi");
const clone = [...listt.list];
if (clone[0].style.color === "blue") {
clone[0].style = { color: "red" };
return { ...listt, list: clone };
} else {
clone[0].style = { color: "blue" };
return { ...listt, list: clone };
}
default :
return {...listt}
}