Issue with React JSX not conditionally rendering

I am working on the following program: Map Board - CodeSandbox

the SearchBox JSX processes the textbox. It generates a prompts array that contains all of the database entries that match the user input.

type “Crf” or “Crawford” and check the console to see this function in action.

Now in the return on line 55, I have the following code:

 return (
      <div className="search-box-container">
          placeholder="Search Database"
      {prompts.length > 0 && <AutoCorrectList prompts={prompts} />}

I only render AutoCorrectList if the length of the prompt is > 0. Otherwise, it should not render anything.

However, even with the prompths length is greater than zero, the AutoCorrectList JSX is never called.

function AutoCorrectList(props) {
  console.log("AutoCorrectList received");

prompts needs to be a state variable.

1 Like

I added it as an state and my life cycle uses the following hooks:

 const inputRef = REACT.useRef(null);
 const [prompts, updatePrompts] = REACT.useState([]);

My React double renders every time the search is changed: Map Board - CodeSandbox

Is this because it renders once due to useRef(), and then the state updating? I also have issues with the state being one behind. However, since it appears to double renders, it then updates on the next render.

Probably just StrictMode doing that. You can remove it to test it (in index). Just put it back when developing.


if you want to know more about why the double renders happen:

The new useState() that it was introduced for has not been implemented yet.
It made working with my old animation library a pain and I had to change to another.

It can help catch a lot of bugs. I think people sometimes mistake the bugs it surface as being an issue with React when in fact it is with the code.

1 Like

@lasjorg @DanielHuebschmann

Removing strict mode seems to solve the double render issue.

The following code produces false with no items in an array. This is despite running updatePrompts(tempPrompts)

    updatePrompts(tempPrompts); // Has 1 or more items
    console.log("Output From Prompt");
    console.log(prompts); // shows []
    console.log(prompts.length > 0); // false

However, passing this state to the JSX AutoCorrectList produces the array as it should be. So my main state for Searchbox is one behind but the passed prompts are up to date. How can make these behaviors be equal?

I know, I see it as a inconvenient side effect that some libraries became harder to work with and I actually found one that suit me better in the process.

I haven’t looked at the code but for logging state, set up a useEffect.

useEffect(() => {
}, [someState, moreState])

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.