React 18

Last Updated: 12/3/2023

useEffect

  • React components should be pure function.
  • A pure function should not have any side effects. Return same result for same input
  • To make components pure, keep any code that makes changes outside of the render phase.
  • Use the effect hook to perform side effects, such as store data in local storage, fetch/save data or updating the DOM. These tasks are not about rendering a component (returning JSX).
  • A piece of code that is changing something outside of the component is called Side Effect.
  • Using the effect hook you can execute a piece of code after a component is rendered. useEffect can be referred as after render. So the function that we pass will be called after each render.
  • Use effect hook at the top level of the components and not inside condition and loops
  • You can call multiple times
  • When you have multiple effects, react will run them in the order after each render
  • The effect hook takes a function that performs the side effect and an optional array of dependencies. Whenever the dependencies change, the effect hook runs again.
const ref = useRef(null);
useEffect(() => {
	if(ref.current)
		ref.current.focus();
});
<input ref={ref} />
useEffect(() => {
  document.title = "React Sample App";
});

Effect Dependencies

  • The function that is passed to effect hook gets executed after each render.
  • If you update state in useEffect it triggers another render. useEffect is going to run again and update state again and goes into infinite loop.
  • You can tell react when to run the useEffect by passing an array of dependencies to the second parameter which is optional.
  • In the dependencies array, you can add one or more variables, which can be props or state and the effect will be dependent on these values. If any of these value changes, react will rerun the effect.
  • If you pass an empty array, that means the effect is not dependent on any values, so it will be executed only once.

Runs in infinite loop

useEffect(() => {
  setProducts(['Shirts', 'Pants'])
});

Run only once

useEffect(() => {
  document.title = "React Sample App";
}, []);

Run whenever prop or state value changes

useEffect(() => {
  document.title = "React Sample App";
}, [props, state]);

Clean up

  • Can optionally return a function that performs clean up
  • Some effects require cleanup to reduce memory leaks. Timeouts, subscriptions, event listeners, and other effects that are no longer needed should be disposed.
  • To clean up any resources that were created by the effect hook, we can include a cleanup function that runs when the component unmounts or the dependencies change.
useEffect(() => {
	let timer = setTimeout(() => {
		setCount((count) => count + 1);
	}, 1000);

	return () => clearTimeout(timer)
  }, []);