useEffect in React

Why is it called useEffect? What does effect mean in this context?

The term “effect” in the context of React’s useEffect hook is referring to side effects that occur within your React component. In computing, a “side effect” is a term that describes when a function or operation modifies state or behavior outside its own scope.

In a React component, side effects could be a number of different things, such as:

  • Fetching data
  • Subscribing to a service
  • Manually manipulating the DOM
  • Setting up a timer
  • Writing to localStorage
  • And more…

These are all things that “reach out” of the component and interact with the broader application or the outside world.

useEffect is a way to handle these side effects in functional components. When you use the useEffect hook in a component, you’re saying “after React renders this component and makes updates to the DOM, it should then run this function (the effect).” The function you pass to useEffect is where you put whatever side effects your component needs to handle.

The reason useEffect is called as such is that it lets you perform “effects” after render. It’s called after every render, including the first one, replacing componentDidMount and componentDidUpdate from class components, and it also provides lifecycle cleanup functionality, similar to componentWillUnmount, by allowing you to return a cleanup function.

So, in summary, the “effect” in useEffect stands for side effects that happen as a result of rendering and updating a component.

In useState where is the state ? Is it in the browser’s memory?

Yes, the state managed by useState is stored in memory managed by the JavaScript runtime environment.

When you call useState, React reserves a “slot” in memory for that state in the current component instance. When the component re-renders, React knows how to find that “slot” and update the state and rerender the component if needed.

It’s worth noting that this state isn’t persisted across page refreshes or browser sessions out of the box. This is because every time you refresh the page, the JavaScript runtime environment restarts and all in-memory state is lost. If you need to persist state across page refreshes, you’ll need to use something like LocalStorage, SessionStorage, Cookies, or a backend database.

Finally, keep in mind that even though the state is in memory, it’s not directly accessible to you as a developer. React uses a system of hooks to allow you to interact with the state without accessing it directly. This ensures that React can maintain control over the rendering process, and that state updates always result in the correct parts of the component re-rendering.