How to use the react.useEffect function in react

To help you get started, we’ve selected a few react examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mui-org / material-ui / docs / src / pages / customization / default-theme / DefaultTheme.js View on Github external
expandPath
        .replace('$.', '')
        .split('.')
        .reduce((acc, path) => {
          const last = acc.length > 0 ? `${acc[acc.length - 1]}.` : '';
          acc.push(last + path);
          return acc;
        }, []),
    );
  }, []);

  const data = React.useMemo(createMuiTheme, []);

  const allNodeIds = useNodeIdsLazy(data);
  React.useDebugValue(allNodeIds);
  React.useEffect(() => {
    if (checked) {
      // in case during the event handler allNodeIds wasn't computed yet
      setExpandPaths(allNodeIds);
    }
  }, [checked, allNodeIds]);

  return (
    <div>
       {
              setChecked(newChecked);
              setExpandPaths(newChecked ? allNodeIds : []);</div>
github segmentio / typewriter / src / cli / commands / version.tsx View on Github external
export const Version: React.FC = () =&gt; {
	const [isLoading, setIsLoading] = useState(true)
	const [latestVersion, setLatestVersion] = useState('')
	const { handleError } = useContext(ErrorContext)
	const { exit } = useApp()

	useEffect(() =&gt; {
		async function effect() {
			try {
				let options: latest.Options = {}

				// If the user is on a pre-release, check if there's a new pre-release.
				// Otherwise, only compare against stable versions.
				const prerelease = semver.prerelease(typewriterVersion)
				if (prerelease &amp;&amp; prerelease.length &gt; 0) {
					options = { version: 'next' }
				}

				const latestVersion = await latest('typewriter', options)
				setLatestVersion(latestVersion)
			} catch (error) {
				// If we can't access NPM, then ignore this version check.
				handleError(error)
github streetmix / streetmix / assets / scripts / ui / Toasts / ToastContainer.jsx View on Github external
})
      // Height going to zero allows subsequent messages to "slide" upwards
      // We also need to animate the margin between toasts
      await next({
        height: 0,
        marginTop: '0px'
      })
    },
    onRest: (item) =&gt; setItems(state =&gt; state.filter(i =&gt; i.key !== item.key)),
    // When state is leave, this returns an array of three configs.
    // Each item in the array applies to each of the `next` calls in the `leave` function, I think.
    // So the first config sets the duration for the `life` property.
    config: (item, state) =&gt; (state === 'leave' ? [{ duration: timeout }, config, config] : config)
  })

  useEffect(() =&gt; void setMessages(item =&gt; setItems(state =&gt; [...state, { key: id++, ...item }])), [setMessages])

  return (
    <div>
      {transitions.map((message) =&gt; {
        const { item, props: { life, ...style } } = message
        const setRef = ref =&gt; ref &amp;&amp; refMap.set(item, ref)
        const handleClose = (event) =&gt; {
          event.stopPropagation()
          cancelMap.has(item) &amp;&amp; cancelMap.get(item)()
        }

        let childComponent

        switch (message.item.component) {
          case 'TOAST_UNDO':
            childComponent = </div>
github petecorreia / react-circular-input / src / useCircularDrag.ts View on Github external
onChange(nearestValue)
	}

	const handleMove = (e: MouseEvent | TouchEvent) => {
		stopEvent(e)
		const nearestValue = getValueFromPointerEvent(e)
		onChange(nearestValue)
	}

	const handleEnd = (e: MouseEvent | TouchEvent) => {
		stopEvent(e)
		setDragging(false)
	}

	// we can't just use React for this due to needing { passive: false } to prevent touch devices scrolling
	useEffect(() => {
		if (!ref.current) return
		addStartListeners(ref.current, handleStart)
		return () => {
			if (!ref.current) return
			removeStartListeners(ref.current, handleStart)
		}
	}, [ref])

	useEffect(() => {
		if (!isDragging) return
		addListeners(handleMove, handleEnd)
		return () => {
			removeListeners(handleMove, handleEnd)
		}
	}, [isDragging])
github meicai-fe / fe-training / react-hooks-guide / src / examples / second / Pure2.js View on Github external
function useCount() {
  const [count, setCount] = useState(0);
  console.log(`what is hooks count now: ${count}`);

  useEffect(() => {
    console.log('call effect');
    return () => {
      console.log('call clean up');
    }
  })

  return {
    count, setCount
  }
}
github ewels / MegaQC / src / admin.js View on Github external
filter_groups: { keyForAttribute: attr =&gt; attr },
      reports: { keyForAttribute: attr =&gt; attr },
      uploads: { keyForAttribute: attr =&gt; attr },
      report_meta: { keyForAttribute: attr =&gt; attr },
      favourites: { keyForAttribute: attr =&gt; attr },
      dashboards: { keyForAttribute: attr =&gt; attr },
      report_meta_types: { keyForAttribute: attr =&gt; attr },
      users: { keyForAttribute: attr =&gt; attr }
    },
    headers: {
      access_token: token,
      Accept: "application/vnd.api+json"
    }
  });

  useEffect(() =&gt; {
    const client = getClient();
    getToken(client).then(token =&gt; {
      setToken(token);
    });
  }, []);

  if (token === null) return null;
  else
    return (
github LedgerHQ / ledgerjs / packages / create-dapp / template / src / SimpleStoreContract.js View on Github external
export const useSimpleStorageValue = simpleStorage => {
  const [value, setValue] = useState(null);

  useEffect(() => {
    if (!simpleStorage) return;

    let unmounted;

    async function main() {
      const value = await simpleStorage.get();
      if (unmounted) return;
      setValue(value);
    }
    main();

    return () => {
      unmounted = true;
    };
  }, [simpleStorage]);
github bsonntag / react-use-promise / src / index.js View on Github external
function usePromise(promise, inputs) {
  const [{ error, result, state }, dispatch] = useReducer(reducer, {
    error: undefined,
    result: undefined,
    state: states.pending
  });

  useEffect(() => {
    promise = resolvePromise(promise);

    if (!promise) {
      return;
    }

    let canceled = false;

    dispatch({ type: states.pending });

    promise.then(
      result => !canceled && dispatch({
        payload: result,
        type: states.resolved
      }),
      error => !canceled && dispatch({
github chakra-ui / chakra-ui / packages / chakra-ui / src / useNumberInput / index.js View on Github external
function useLongPress(callback = () => {}, speed = 200) {
  const [isPressed, setIsPressed] = useState(false);

  useEffect(() => {
    let timerId;
    if (isPressed) {
      timerId = setTimeout(callback, speed);
    } else {
      clearTimeout(timerId);
    }

    return () => {
      clearTimeout(timerId);
    };
  }, [isPressed, callback, speed]);

  const start = useCallback(() => {
    callback();
    setIsPressed(true);
  }, [callback]);
github Altinn / altinn-studio / src / Altinn.Apps / AppFrontend / react / altinn-app-frontend / src / components / base / FileUploadComponent.tsx View on Github external
if (!attachmentToDelete.uploaded) {
        return state;
      }
      attachmentToDelete.deleting = true;
      const newList = state.slice();
      newList[action.index] = attachmentToDelete;
      return newList;
    }
    return state;
  }

  const currentAttachments: IAttachment[] = useSelector(
    (state: IRuntimeState) => state.attachments.attachments[props.id] || emptyArray,
  );

  React.useEffect(() => {
    dispatch({ type: 'replace', value: currentAttachments });
  }, [currentAttachments]);

  const getComponentValidations = (): IComponentValidations => {
    let validationMessages = props.componentValidations;
    validationMessages = JSON.parse(JSON.stringify(validationMessages || {}));
    if (!validationMessages || !validationMessages.simpleBinding) {
      validationMessages = {
        simpleBinding: {
          errors: [],
          warnings: [],
        },
      };
    }
    if (!validations || validations.length === 0) {
      return validationMessages;