Modern React.js is prone to too many re-renders if done wrong.
One part that is of a higher risk, are contexts.
The reason for this is how they cause re-renders in children of the context provider.
The re-render is typically done due to a state change via useState or useReducer.
As long as this is done properly, this should not be an issue.
However, in more complex contexts, the data could change reference at some levels but not at others.
There is also the issue of setters in contexts. If a setter is used, should the whole object change reference? The function too? Just the main data reference?
Just to make sure, I asked Bard AI to get some inspiration:
Does a react.js reducer need to return a new object each time?
In React with Redux, reducers ideally should return a new object every time, even if there’s no state change. Here’s why:
-
Immutability: This is a core principle in Redux. By returning a new object, you avoid accidentally modifying the existing state. This makes reasoning about state updates easier and prevents unintended side effects.
-
Performance Optimization: Redux relies on shallow comparison to detect state changes. Returning a new object, even an identical one, forces a re-render of components that rely on that state. This can trigger optimizations in React’s virtual DOM, potentially improving performance.
There might be cases where the reducer can return the original state if there’s no change. However, it’s generally considered a best practice to always return a new object. This ensures consistency and avoids potential bugs.
Here are some ways to achieve this:
-
Spread Operator (...
): This is a common approach. You can copy the existing state and modify specific properties within the new object.
-
Immutable.js Library: This library provides helper functions for creating and manipulating immutable data structures.
Remember, even if the reducer doesn’t modify the state, returning a new object can still benefit readability and maintainability of your code.
However, the reference to the context changes each time, and I am using the reference in a useCallback function, for example: context.setData, what should I do?
You’re right, there’s a potential issue when using useCallback
with a context that changes on every render. Here’s how to address it:
The Problem:
useCallback
memorizes a function based on its reference. If the context containing setData
changes on every render, useCallback
will create a new function reference each time. This defeats the purpose of useCallback
as child components will receive a new function on every render, even if the logic within the function hasn’t changed.
Solutions:
-
Prevent Context from Changing Unnecessarily:
- Check if your context truly needs to change on every render. If it holds static data or only updates occasionally, consider refactoring it to update less frequently.
-
Extract setData
Outside of useCallback
:
- Move the logic for getting
setData
from the context outside of the useCallback
function. This way, you only capture the reference to the function itself, not the context that might change.
Here’s an example:
const MyContext = React.createContext();
const MyComponent = () => {
const context = useContext(MyContext);
const setData = context.setData;
const memoizedFunction = useCallback(() => {
setData();
}, []);
return (
{}
);
};
-
Combine useCallback
with useMemo
:
- In some cases, you might need to keep the
setData
reference within the useCallback
function. Here, you can combine useCallback
with useMemo
to create a memoized function that references the current setData
function from the context.
const memoizedFunction = useCallback(() => {
const context = useContext(MyContext);
const setData = context.setData;
return () => {
setData();
}
}, [context]);
Choosing the Right Approach:
The best solution depends on your specific use case. If you can prevent unnecessary context updates, that’s ideal. Otherwise, consider extracting setData
or using the combination of useCallback
and useMemo
.
Should the context reference change on every data change? Even if for example I have context data of { data, setData } where only data is the data to be stored and referenced?
No, the context reference ideally shouldn’t change on every data change, especially in the scenario you describe where data
is the primary data store and setData
is the update function. Here’s why:
-
Unnecessary Re-renders: If the context reference changes with every data update, components that rely on useContext
will re-render even if the data itself hasn’t changed. This can lead to performance issues, especially for deeply nested components.
-
useCallback
Issues: As you mentioned previously, useCallback
relies on reference equality. Changing the context reference with every update will defeat the purpose of useCallback
in child components.
Better Practices for Context Updates:
Here are some approaches to keep the context reference stable while updating data:
-
Immutable Updates:
- Update the
data
property within the context by creating a new object with the updated value. You can use the spread operator (...
) to achieve this:
const MyContext = React.createContext({ data: [], setData: () => {} });
const updateData = (newData) => {
dispatch({ type: 'UPDATE_DATA', data: newData });
};
const reducer = (state, action) => {
switch (action.type) {
case 'UPDATE_DATA':
return { ...state, data: action.data };
default:
return state;
}
};
-
Context with Reducer:
- If your data updates are complex, consider using a reducer with your context. This allows you to manage state updates in a more predictable way and keeps the context reference stable.
-
useMemo
for Selective Updates:
- In some cases, you might only need to re-render specific parts of your UI based on data changes. Here, you can use
useMemo
to create a memoized value derived from the context data. This memoized value will only update when its dependencies (specific parts of the data) change, preventing unnecessary re-renders.
By following these practices, you can ensure that your context reference remains stable while effectively managing data updates in your React application.
As can be seen by this dialogue:
- The value returned from contexts does not need to change.
- The setter function does not need to change.
- Any reducers used should return a new reference.
- Therefore, the data reference should be expected to change on update and so can be watched for changes.