score:208
You need to use setInterval
to trigger the change, but you also need to clear the timer when the component unmounts to prevent it leaving errors and leaking memory:
componentDidMount() {
this.interval = setInterval(() => this.setState({ time: Date.now() }), 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
score:0
So you were on the right track. Inside your componentDidMount()
you could have finished the job by implementing setInterval()
to trigger the change, but remember the way to update a components state is via setState()
, so inside your componentDidMount()
you could have done this:
componentDidMount() {
setInterval(() => {
this.setState({time: Date.now()})
}, 1000)
}
Also, you use Date.now()
which works, with the componentDidMount()
implementation I offered above, but you will get a long set of nasty numbers updating that is not human readable, but it is technically the time updating every second in milliseconds since January 1, 1970, but we want to make this time readable to how we humans read time, so in addition to learning and implementing setInterval
you want to learn about new Date()
and toLocaleTimeString()
and you would implement it like so:
class TimeComponent extends Component {
state = { time: new Date().toLocaleTimeString() };
}
componentDidMount() {
setInterval(() => {
this.setState({ time: new Date().toLocaleTimeString() })
}, 1000)
}
Notice I also removed the constructor()
function, you do not necessarily need it, my refactor is 100% equivalent to initializing site with the constructor()
function.
score:0
Owing to changes in React V16 where componentWillReceiveProps() has been deprecated, this is the methodology that I use for updating a component. Notice that the below example is in Typescript and uses the static getDerivedStateFromProps method to get the initial state and updated state whenever the Props are updated.
class SomeClass extends React.Component<Props, State> {
static getDerivedStateFromProps(nextProps: Readonly<Props>): Partial<State> | null {
return {
time: nextProps.time
};
}
timerInterval: any;
componentDidMount() {
this.timerInterval = setInterval(this.tick.bind(this), 1000);
}
tick() {
this.setState({ time: this.props.time });
}
componentWillUnmount() {
clearInterval(this.timerInterval);
}
render() {
return <div>{this.state.time}</div>;
}
}
score:3
i myself like setTimeout
more that setInterval
but didn't find a solution in class based component .you could use sth like this in class based components:
class based component and setInterval:
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {
date: new Date()
};
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
this.state.date.toLocaleTimeString()
);
}
}
ReactDOM.render(
<Clock / > ,
document.getElementById('app')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app" />
function based component and setInterval:
https://codesandbox.io/s/sweet-diffie-wsu1t?file=/src/index.js
function based component and setTimeout:
score:4
class ShowDateTime extends React.Component {
constructor() {
super();
this.state = {
curTime : null
}
}
componentDidMount() {
setInterval( () => {
this.setState({
curTime : new Date().toLocaleString()
})
},1000)
}
render() {
return(
<div>
<h2>{this.state.curTime}</h2>
</div>
);
}
}
score:9
In the component's componentDidMount
lifecycle method, you can set an interval to call a function which updates the state.
componentDidMount() {
setInterval(() => this.setState({ time: Date.now()}), 1000)
}
score:83
@Waisky suggested:
You need to use
setInterval
to trigger the change, but you also need to clear the timer when the component unmounts to prevent it leaving errors and leaking memory:
If you'd like to do the same thing, using Hooks:
const [time, setTime] = useState(Date.now());
useEffect(() => {
const interval = setInterval(() => setTime(Date.now()), 1000);
return () => {
clearInterval(interval);
};
}, []);
Regarding the comments:
You don't need to pass anything inside []
. If you pass time
in the brackets, it means run the effect every time the value of time
changes, i.e., it invokes a new setInterval
every time, time
changes, which is not what we're looking for. We want to only invoke setInterval
once when the component gets mounted and then setInterval
calls setTime(Date.now())
every 1000 seconds. Finally, we invoke clearInterval
when the component is unmounted.
Note that the component gets updated, based on how you've used time
in it, every time the value of time
changes. That has nothing to do with putting time
in []
of useEffect
.
score:95
The following code is a modified example from React.js website.
Original code is available here: https://reactjs.org/#a-simple-component
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = {
seconds: parseInt(props.startTimeInSeconds, 10) || 0
};
}
tick() {
this.setState(state => ({
seconds: state.seconds + 1
}));
}
componentDidMount() {
this.interval = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
formatTime(secs) {
let hours = Math.floor(secs / 3600);
let minutes = Math.floor(secs / 60) % 60;
let seconds = secs % 60;
return [hours, minutes, seconds]
.map(v => ('' + v).padStart(2, '0'))
.filter((v,i) => v !== '00' || i > 0)
.join(':');
}
render() {
return (
<div>
Timer: {this.formatTime(this.state.seconds)}
</div>
);
}
}
ReactDOM.render(
<Timer startTimeInSeconds="300" />,
document.getElementById('timer-example')
);
Source: stackoverflow.com
Related Query
- Update React component every second
- Changing/shuffling text every 1.5 second in a react component
- React JS, How to only allow component to update once per second
- How to update a clock every second in React js recursively?
- React router is unmounting and remounting child component on every update
- How to update state in React before every component render?
- Using react hooks to usestate every second and update DOM only if state has changed
- Can't perform a React state update on an unmounted component
- React useEffect causing: Can't perform a React state update on an unmounted component
- React-hooks. Can't perform a React state update on an unmounted component
- React Warning: Cannot update a component from inside the function body of a different component
- Update component state from outside React (on server response)
- How to test a prop update on React component
- onChange event for React child component to update state
- React setState can only update a mounted or mounting component
- Update React Context using a REST Api call in a functional component
- Update React component by dispatching action from non-react component
- How to update the state of a sibling component from another sibling or imported component in REACT
- React + Redux: Component does not update
- React router Link not causing component to update within nested routes
- Warning: Can't perform a React state update on an unmounted component. In a functional component
- How to trigger a CSS animation on EVERY TIME a react component re-renders
- React Apollo: Dynamically update GraphQL query from Component state
- Should every react component have it's own stylesheet?
- Using shouldComponentUpdate for block component re-render every second
- Reactjs - Update options by hitting API on every input change in Autocomplete component (Material UI)
- React hooks function component prevent re-render on state update
- Avoid rerendering every component in list while updating only one in React
- Call API Every X Seconds in React Function Component
- How to update props of React Component rendered using ReactDOM.render()
More Query from same tag
- My react app is crashing even after error handling. Why is this happening?
- Why can't I run Webpack with React?
- How to download file directly in node response in react?
- Is it mandatory to pass props to react functional component?
- how to increase waiting timeout from 30000 ms to 60000 ms of npm installing time in ubuntu
- how to pass a list from flask backend to a reactjs frontend?
- Custom Hook with Generic Types TypeScript
- Is this how you properly add a new item to the state?
- React - Calling a specific function when 'Enter' key is pressed
- How to test a function with different inputs
- Preload data in reactjs component
- Chartjs 3.x - How to duplicate X axis on both sides of horizontal bar chart with only 1 dataset?
- How to adjust valid input check method for SpinButton?
- How to handle multiple radio button groups in one component in reactjs?
- React: Data not showing on the browser but it shows on the console
- "article seed # 0" => "article-seed-0" to navigate to other Page with that url?
- React responsive Navbar
- Two components with the same state/functions but different UI
- How to prevent Gatsby image from blurring a logo with every reload?
- React - How do i persist a page url after refresh?
- ReactJS mixed all css
- React TypeError: Cannot read properties of undefined (reading 'params')
- Getting error while trying to render array of object in react js
- Jest jest.fn it's being called but the expect fails
- Robust testing with jest and enzyme
- Storing an Array of Objects in Redux-Toolkit - Array is logging empty but it isn't
- How can I make an axios get request wait before rendering my react component
- How to re-render the parent component when the child component adds an element to the database?
- How to Validate "Digit" Range on handle validation in ReactJS
- Getting an Error: Before running a Saga, you must mount the Saga middleware on the Store using the applyMiddleware