Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

useEffect time elapsed

const Clock = ({ dispatch, inProgress, ticksElapsed }) => {
  React.useEffect(() => {
    const progressTimer = setInterval(function () {
      inProgress && dispatch({ type: 'CLOCK_RUN' });
    }, 500);
    return () =>
      //inprogress is stale so when it WAS true
      //  it must now be false for the cleanup to
      //  be called
      inProgress && clearInterval(progressTimer);
  }, [dispatch, inProgress]);

  return <h1>{ticksElapsed}</h1>;
};

const App = () => {
  const [inProgress, setInProgress] = React.useState(false);
  const [ticksElapsed, setTicksElapsed] = React.useState(0);
  const dispatch = React.useCallback(
    () => setTicksElapsed((t) => t + 1),
    []
  );
  return (
    <div>
      <button onClick={() => setInProgress((p) => !p)}>
        {inProgress ? 'stop' : 'start'}
      </button>
      <Clock
        inProgress={inProgress}
        dispatch={dispatch}
        ticksElapsed={ticksElapsed}
      />
    </div>
  );
};
ReactDOM.render(<App />, document.getElementById('root'));
Comment

PREVIOUS NEXT
Code Example
Javascript :: node.js how to install a custom version of packgage 
Javascript :: how to only register one click on nested component and not parent component in react js 
Javascript :: how to use mixed quotes in a sentence in js 
Javascript :: concatenate state with previous state in react redux 
Javascript :: how to take out text from array of strings in react 
Javascript :: jquery timeout 
Javascript :: alpine js x:bind href link 
Javascript :: node and bash together 
Javascript :: javascript reduce array of objects group by property 
Javascript :: puppeeter pdf desktop 
Javascript :: ionic react exit app 
Javascript :: ngreadonly 
Javascript :: installing toast for angular projects 
Javascript :: javascript compare two arrays of objects return difference 
Javascript :: which element occours when a DOM element recieve the coursor 
Javascript :: map object keys javascript 
Javascript :: React uses _____________ syntax. 
Javascript :: Fromdata 
Javascript :: this.$moment.tz.guess() not working mozilla 
Javascript :: jquery textfill example 
Javascript :: dynamically define routes separated in different pages for React 
Javascript :: top 50 mcq que in javascript 
Javascript :: fade animation vuetify js 
Javascript :: getComments 
Javascript :: &amp;nbsp replace javascript 
Javascript :: react native debug server host & port for device 
Javascript :: jquery validate min and max value 
Javascript :: react using pre new Date 
Javascript :: Will Yield function Model 
Javascript :: validar fecha jquery 
ADD CONTENT
Topic
Content
Source link
Name
8+6 =