Why isn't my useState function initializing with the default value?

Below is a simplified version of my code:

  const handleEdit = async (event) => {
    event.preventDefault();
    if (parentLayer === 0) {
      const { content, attachment} = event.target.elements;
      let contentValue = content.value;
      setEditedContent(contentValue);
      let attachmentValue = attachment.files[0];
      if (contentValue !== content) await updateContent(contentValue);
      if (attachmentValue !== undefined && parentLayer === 0) await updateImg(attachmentValue);  
    } else {
      const { content } = event.target.elements;
      let contentValue = content.value;
      setEditedContent(contentValue);
      if (contentValue !== content) await updateContent(contentValue);
    }
  };


const EditForm = (props) => {
  const { content, parentLayer } = props;

  const [editedContent, setEditedContent] = useState(content);

  <div className='discussion'>
    <form className='edit-discussion' onSubmit={handleEdit}>

      {parentLayer === 0
         ?
          // Can update img
          <input type='file' id='files' name='attachment'/>
          <textarea defaultValue={editedContent} required/>
          <button type='submit' value='Submit'>submit</button>
         :
          <textarea defaultValue={editedContent} required/>
          <button type='submit' value='Submit'>submit</button>
   </form>
  </div>


}

In this case, when parentLayer equals 0, the editedContent defaults to {content} which comes from props.

If parentLayer is greater than 0, editedContent is an empty string. However, upon checking with console, {content} holds the correct value.

My question is, why can't the useState set the default value in the second condition?

Here's a screenshot of my program for better visualization:

This is a Reddit-like site, please excuse the unfinished interface: https://i.sstatic.net/uxKln.jpg

During editing, you can see that only the parent layer has the defaultValue: https://i.sstatic.net/ck89g.jpg

Why does React behave in this way?

Update:
The structure of my React program is as follows:

Mainpage => discussion page => By calculation get parentLayer value => when parentLayer equals 0 render the top discussion block, otherwise render the rest of the discussion blocks. Both the top block and the rest block have an editform component.

Essentially, React will render only one page component but many editform subcomponents.

To give a complete visual design, It resembles Reddit layout (apologies for the unfinished design): https://i.sstatic.net/52nfi.jpg

Answer №1

Apologies for the lack of clarity in my question, but I believe I have identified the cause of this behavior:

{content} is being passed as a prop, and information from this source

Suggests that: useState does not reset on prop change.

Therefore, each time the content within the parent component changes, the editform subcomponent will maintain the same state.

To address this issue, I made the following adjustments (only changes highlighted):


const [editedContent, setEditedContent] = useState('');

  useEffect(() => {
    setEditedContent(content);
  }, [content]);

This will trigger a re-render of the component whenever a new layer is added.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps for serializing multiple sortable items and subitems using jQuery

I found a solution on Stack Overflow that allows me to sort items and subitems using jQuery UI sortable. Everything is sorting correctly, but I'm struggling with serializing the data so that I can update the database accordingly. You can view my curr ...

External CSS file unable to load background image as referenced

I am facing an issue with this code in my external CSS file as it doesn't seem to work at all. Strangely, when I move it internally, everything functions perfectly. Any thoughts on what could be causing this discrepancy? html { background-image:url(i ...

Issue with fortawesome icon: relative and absolute positioning not functioning as expected

I have utilized a diamond symbol from the Fort Awesome icon collection and noticed that when I target the i tag in my CSS, the icon becomes highlighted (see screenshot attached). However, I am encountering issues with relative and absolute positioning not ...

Manipulate a 3D shape by transforming both the x and y axes using jQuery's mousemove

I am trying to create a 3D element that rotates on both the x and y axes based on the position of the mouse on the screen. While I have successfully achieved this effect using either the X or Y position, I am struggling to make it work simultaneously for b ...

Accessing lifecycle methods for React components in TypeScript as a member

Utilizing the typescript react starter for tsx-driven react implementations requires specifying member access (public, private, protected) for any method utilized within a class component. This requirement stems from, I believe, the tslint.json file. Can ...

Assigning background colors based on the data stored in a specific field of a MySQL database

I have successfully implemented a Ticketing System using PHP and MySQL database. The view tickets page displays each ticket from the database along with its priority level, which can be Low, Normal or High. Currently, the priority value pulled from the d ...

Discrepancy between keydown event and button click functionality

Whenever I click the search button, the sendTitle() function executes flawlessly. However, when I press the enter key (keyCode == 13), the sendTitle() function consistently throws a catch error response (alert cannot connect). I am curious if anyone unders ...

The width of the Apex chart is either overflowing or not stretching properly

I'm currently utilizing apexcharts within a vue environment. My goal is to have the sparkline graph expand to occupy 100% of its parent's width. Here is what I attempted: <div> <apexchart :options="chartOptions" :ser ...

Is there a way to adjust the height of a turnjs page?

I am currently utilizing the Turn.js flip library and I need to adjust the height of the turnjs page. The current setup calculates the height of the page based on the client's height, but now I want to change it to a specific value like 700px. How can ...

Is there a way to ensure that my off-screen menu functions properly across all web browsers?

I am in the process of developing a website for my school project and everything has been going smoothly so far. However, I encountered an issue when trying to open the site on different web browsers. The off-screen menu that I created using HTML/CSS seems ...

Struggling with customization of CSS for a.class:hover in jQuery mobile

Currently, I am engaged in developing a project using the jquery mobile framework 1.0. My goal is to create a gradient background effect on the anchor defined below as .grid-anchor when users hover over it. However, despite my efforts, I have been unsucces ...

Utilizing the object Promise within JSX: A comprehensive guide

When I receive a Promise object from axios in my code, I encounter an error when trying to use it in JSX. The error states: "Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an ...

Dynamic content in CSS horizontal alignment

In a parent div with fixed width, I have dynamically created divs that I want to distribute horizontally without knowing the exact number of elements. I tried using the "Using inline-block and justified text" technique from a CSS Tricks page but it did not ...

Displaying a base64 image in a new tab with JavaScript on iOS devices

Currently, I am receiving base64 data for an image and would like to open it in a new tab. To achieve this, my code looks something like this: var window = new window(); window.open("<iframe src="+base64Url+"); Interestingly, this method works perfec ...

What is the best way to divide a div by 6?

Is there a way to create six equally sized divisions within a div without using tables or plugins? <div> <div></div> <div></div> <div></div> <div></div> < ...

Looking to use Jquery to translate an image both on and off the screen with full width and height?

Imagine a scenario where a full-screen image remains hidden upon page load. When a user clicks a link, the image smoothly slides up from the bottom of the page. Upon clicking the image, it should smoothly move off the page as if it were being translated do ...

Centering text using CSS Bootstrap

Hey everyone, I've been attempting to center my text using Bootstrap, but for some reason it's not working. Can someone help me figure out what's going on? <footer class="row p-1 mt-3 bg-primary text-white"> <p class= ...

What is the best way to remove a certain length of old data from an array while adding new data, all while maintaining a maximum array length?

Received a dataset from an API in the following format: samples: [ { key: 'I', values: [ { timing: '12356timingdatething', reading: -37.1234 }, { timing: '12356timingdatething', reading: -32.1 ...

Troubleshooting issues with applying a class on load using JavaScript

I am new to Javascript and I am trying to add a class to an element when the page loads. Specifically, I want to change the background color of the element as a test. However, I keep running into the error message "Uncaught TypeError: Cannot read property ...

The React page is stuck in a perpetual cycle of reloading every single second

After developing an invoice dashboard system using React, I encountered a recurring issue with a similar version of the app built on React. Even after commenting out all API calls, the useEffect(), the page kept reloading every second. Any advice or sugge ...