Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - Update Component Each Second Without Re Rendering Whole Form

React and Redux - kinda new to React, just looking for resources, links to better understand this specific problem.

TLDR; How to update sub component each second without re rendering parent component? But parent needs to get the state at least when submit button is clicked.

I have a component with a form and several form fields. One of the fields is a date picker. The date picker field, by default, is ticking for each second, but the user has the ability to manually set the time. When the user 'submits' the form it will take the time in the field, whether it was auto populating each second or the user manually manipulated the date.

Each time the date picker is changed, every second or manually, my entire component re renders. This is not a very big deal except I have a responsive bootstrap table, that when scrolled to the right will re draw back to the left every second, or when the ticking clock updates each second.

Initially, I was using setState() to keep this value updated, but after running into this issue I set up an action and reducer in redux, but I get the same behavior.

Here is the code used to update the state (and redux method commented, currently)

export const onInputChangeCommon = function (event) {
  const target = event.target;
  const value = target.type === 'checkbox' ? target.checked : target.value;
  const name = target.name;
  this.setState({
    [name]: value
  });

  if (name === 'showHideCustomDatetime' && value) {
    this.interval = setInterval(this.getTime, 1000);
  } else if (name === 'showHideCustomDatetime' && !value) {
    clearInterval(this.interval);
  }
}

export const getTime = function () {
  const time = moment().format(`${this.state.timeFormat.date} ${this.state.timeFormat.time}`);
  // this.props.setEnterTimeCustomDatetime(time);
  this.setState({
    enterTime: time,
    isInvalidDate: false
  });
}

appreciate any insights

EDIT Check out this CodePen. https://codepen.io/anon/pen/EbNqpJ?editors=1111

I dont understand how to get the time from the child component back to the parent.

like image 890
arodjabel Avatar asked Feb 25 '26 12:02

arodjabel


2 Answers

You should split your component into multiple components. Then, you can use the lifecycle method shouldComponentUpdate() to verify if the component should re-render. Note that your component should be stateful in order to use lifecycle.

like image 105
Tiago Alves Avatar answered Feb 28 '26 02:02

Tiago Alves


React calculates virtual doms of all components and rerenders only the one which have changes (thus, has minimal changes to main DOM). So, split your main component into multiple components which you would want to rerender separately according to their state changes.

like image 22
apsdehal Avatar answered Feb 28 '26 02:02

apsdehal