A look behind the scenes of React and optimizations techniques

In React apps you work with components, typically with function components in modern React. Those components have one job in the end, and that is the JSX code, which they return. This tells React what the output of that component should be. Now in your React components, you can work with state, or with props, or with context, though props and context as I mentioned, all come down to state changes in the end, to make changes to a component and to make changes to the data that affect this component or that affects parts of your application.

Whenever you change state in a component that component where the state changed is reevaluated and that simply means that the component function is executed again. So all the component code runs again, and therefore we get a new output. This might actually be exactly the same output as before, but it could also look different. For example, if suddenly a pharagraph is rendered or not, or some things need to be changed between the renders. React simply takes the result of the latest evaluation and compares it to the previous evaluation's result and it does that for all affected components. The changes are sent to React DOM, and React DOM takes these changes and apply them to the real DOM in the browser, and really only those changes, nothing else.

Now, when React reevaluates a component, it does not just reevaluate that component, but since it reruns the entire function and therefore all the rebuilds, this JSX code rebuilds the output for this latest snapshot, so to say. It will also rerun all components that you have in this JSX code. Now to avoid unnecessary re-executions of child components, you can use React.memo to tell React: "hey, please only execute this component function again if the props really changed, so if we got real new values in there." If we got no new values, please don't re-execute this function. Now since reevaluating a component means that the entire component function runs again, that can have strange effects if you're not aware of the fact that this really means that everything in this function runs again. And therefore, id you, for example create functions in the functions and you pass those functions through props to other components, you will indeed get a new function object and even React.memo will then not be able to help you because objects are reference values and comparing them with equal signs which is what React.memo does under the hood, will not work. For primitive values, you will therefore not have that problem. That's where useCallback comes in and can help you, because with useCallback, you can tell React that it should store a function and not to recreate it when the surrounding function runs again, as long as certain dependencies didn't change.

Category: React Tags: #react, #performance