Search code examples
javascriptreactjscomponents

Using ++ operator in react component


import React, { useState } from "react";
// import styles sheet:
import "./css/CommentBlock.css";

// import profile avatars:
import gamer from "./icons/gamer.png";
import man1 from "./icons/man (1).png";
import man from "./icons/man.png";
import user from "./icons/user.png";
import woman1 from "./icons/woman (1).png";
import woman from "./icons/woman.png";

let icons = [gamer, man1, man, user, woman1, woman];
let index = 0;

function CommentBlock(props) {
  // JS object destructuring:
  let { name, comment } = props;
  index ++;
  console.log(index);

  return (
    <li className="comment-block">
      <div className="avatar">
        <img src={icons[index % icons.length]} alt={name} />
      </div>
      <div className="comment-info">
        <h4 className="user-name">{name}</h4>
        <p className="comment-context">{comment}</p>
      </div>
    </li>
  );
}

export default CommentBlock;

index value: 1 3 5 7 9 11 ...

I'm really confused about ++ operator in react component. I have 7 comment block but when I use index ++ in my component. I expect that index increases just one time. but index value increased for two times.

I want to know how solve this problem ?


Solution

  • The problem you are facing is about react render (the lifecycle of react), and the fact that in development mode, react uses Strict Mode, which causes a double render of your component, moreover, you are using a variable to hold your data, any render of your component cause the index increase, I think for your case you show use the react's state.

    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 Note:

    This only applies to development mode. Lifecycles will not be double-invoked in production mode.

    https://reactjs.org/docs/strict-mode.html#gatsby-focus-wrapper

    Taken from react official docs you can read about the strict mode and more explained about the state and the lifecycle of react.