useState & useEffect in React

UseState

Changes to the state (e.g. updating a value via useState) will cause the given component to re-render. There is an algorithm that determines which parts of the page need to re-render when something changes.

export const MyComponent = (props: any) => {
	const { configurations, aUsefulNumber, deviceState } = props;
	// Changing this state object will cause the component to re-render
	const [showErrorPopup, setShowErrorPopup] = useState(false);
	
	// This useEffect callback fires whenever 'deviceState' changes
	useEffect(() => {
		// If the device state is some error, show error modal via the state
		if (deviceState && deviceState == HardwareModes.ErrorState) {
			setShowErrorPopup(true);
		}
	}, [deviceState]);
	
    return <>
		// Boolean is resolved being in the '{}' block, hides modal if false
		{showErrorPopup &&
			<ErrorPopupModal />
		}
	</>;
};

UseEffect

useEffect can be used to update or change things on a page and/or in the component dynamically. Generally, one should see if it makes more sense to put whatever is being done in useEffect callback into a state object — it can be a faulty design habit to get into using this instead of the state, since that will re-render the page anyway.

useEffect(() => {
	// This callback will fire every time the given dependency object changes
}, [AppManager.Data]);
useEffect(() => {
	// This callback will fire once when the component is constructed
}, []);
useEffect(() => {
	// This callback will fire every time the page is rendered, i.e. many times
});

web_dev react typescript javascript