Why useDispatch re-renders parent components? - javascript

I'm using useDispatch hook (from Redux) in onSelect callback in the Tree component (from Ant library):
export const MyComponent = () => {
const dispatch = useDispatch();
const onSelect = (selectedNode) => {
const selectedItem = selectedNode[0];
dispatch(fetchSelectedItems(selectedItem));
};
return
<Tree
onSelect={onSelect}
>
<TreeNode .. />
<TreeNode .. />
<TreeNode .. />
</Tree
}
export const fetchSelectedItems = (selected: string) =>
(dispatch) =>
axios({
url: `/api/items?id=${selected}`,
method: 'GET',
}).then(response => {
dispatch(fetchSelectedItemsSuccess(response.data))
}).catch((error: any) => {throw(error)});
Why does useDispatch re-render parent components? Is there any way to prevent from this? I tried useCallback like it's in Redux documentation but this solution is to prevent child components from re-rendering, not parents.

It looks like my assumption in the comment was correct.
So I will show you the workaround.
You can extract the part that uses clickValue in the container to another component, say ClickValue.
Doing so will isolate the update to ClickValue component only.
My fork: https://codesandbox.io/s/soanswer60515755-9cc7u
function ClickValue() {
const clickValue = useSelector(state => state.value);
console.log(clickValue);
return clickValue;
}
export default function Container() {
return (
<div className="Container">
<h3>Container</h3>
<ParentComponent />
<ClickValue />
</div>
);
}
Check out the profile result below.

I would think that on every render you are redeclaring the onSelect function. Functions are reference types. Passing that redeclared function with its new reference on ever render will cause a rerender. Perhaps you should look into using context.

My problem with re-rendering components was caused by useSelector used in parent components where I directly refer to state. Most probably because of new result of this selector..
Solution:
I rewrote this selectors with reselect library to make them memoized (it was suggested in one of comments here but I don't know why its've been removed). I did exactly what is in redux documentation about memoized selectors.

Related

Calling function defined within a react function component on a click event form another function component - React.js

I am constructing some node objects in a function(prepareNodes) to pass to React Flow within a functional component A (lets say), and I have defined a custom node component(CardNode) stateless, which has a button. On button click it should trigger the function(prepareNodes) defined within Component A.
function ComponentA = ({ selectedNodes }) => {
const reactFlowWrapper = useRef(null);
const [elements, setElements] = useState([]);
const [edges, setEdges] = useState([]);
const prepareNode = async (nodeid) => {
//some service calls to fetch data and constuct nodes
setElements([ ...nodes]);
setEdges([...edges]);
}
return (
<ReactFlowProvider>
<div className="reactflow-wrapper" ref={reactFlowWrapper}>
<ReactFlow
nodes={elements}
edges={edges}
//some properties
>
</ReactFlow>
</div>
</ReactFlowProvider>
)
};
export default ComponentA;
function CardNode({ data }) {
const renderSubFlowNodes = (id) => {
console.log(id);
//prepareNode(id)
}
return (
<>
<Handle type="target" position={Position.Top} />
<div className="flex node-wrapper">
<button className="btn-transparent btn-toggle-node" href="#" onClick={() => renderSubFlowNodes(data['id']) }>
<div>
<img src={Icon}/>
</div>
</button>
</div>
<Handle type="source" position={Position.Bottom}/>
</>
);
}
export default CardNode;
I looked for some references online, and most of them suggest to move this resuable function out of the component, but since this function carries a state that it directly sets to the ReactFlow using useState hook, I dont think it would be much of a help.
Other references talks about using useCallback or useRefs and forwardRef, useImperativeHandle especially for functional component, Which I did not quite understand well.
Can someone suggest me a solution or a work around for this specific use-case of mine.
You can add an onClick handler to the each node, and within the node view you call this handler on click.
In the parent Component within the onClick handler you can call prepareNode as needed.
useEffect(() => {
setElements(
elements.map(item => {
...item,
onClick: (i) => {
console.log(i);
prepareNode();
},
})
)},
[]);
The classical approach is to have a parent object that defines prepareNode (along with the state items it uses) and pass the required pieces as props into the components that use them.
That "parent object" could be a common-ancestor component, or a Context (if the chain from the parent to the children makes it cumbersome to pass the props all the way down it).

How to wrap React Hooks dispatch into function outside component

I was wondering if i could wrap dispatch action into function (for example class method). I have this component:
function Product({id}) {
const {state, dispatch} = React.useContext(CartContext);
return (
<button onClick={() => dispatch({type: "remove", payload: id})}>Remove</button>
)
}
What i want to achieve is to replace ugly looking dispatch call into more clear function like this:
<button onClick={() => Cart.remove(id))}>Remove</button>
Is it possible? I've tried by this way but hooks can't be called outside React component.
export default Cart {
static remove = id => React.useContext(CartContext).dispatch({type: "remove", payload: id});
}
What you need is to create a custom hook
const useRemoveCart = () => {
const {state, dispatch} = React.useContext(CartContext);
return id => dispatch({type: "remove", payload: id})
}
And now you can use this hook and call the return of it.
function Product({id}) {
const remove = useRemoveCart()
return (
<button onClick={() => remove(id)}>Remove</button>
)
}
But I don't feel like this is the way to go.
Probably the max thing you could do is create a useCart hook that will return state and dispatch. Creating a custom hook only for one function isn't good, because if you need another function, you will have to do a lot of refactor or create a new hook, and you will have one hook for each function, which will be very bad.
If I was you, I would do this
const useCart = () => React.useContext(CartContext)
Now you don't need to import useContext and CartContext, only import useCart
And probably create variables instead of passing the hole string "remove" which can cause some typos.
const REMOVE_CART = 'remove'
And use it like
dispatch({type: REMOVE_CART, payload: id})
Now you will never have a typo in the 'remove' string because if you do, it will give you an error.
You shouldn't pass dispatch to child components. Child components should typically pass the data back up to the parent, and the parent should solely be responsible for the state in the case. I'd suggest a Helper function in Product that does this.

What is correct way to fix this 'Invalid Hook Call' error in react app?

Well, i have this error
Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
I tried alot of different options to fix this, but i failed.
Here is my code
export const DataInput = () => {
const Post = (testTitle, testText) => {
useFirestore().collection('schedule-data').doc('test').set({
testTitle: testTitle,
testText: testText
})
}
return(
<Button
variant="primary"
onClick={()=> Post(testTitle, testText)}>
POST data
</Button>
Deleted some of code that does not matter
Hooks can only be called while rendering a component, so they need to be in the body of your component.
export const DataInput = () => {
const firestore = useFirestore();
const Post = (testTitle, testText) => {
firestore.collection('schedule-data').doc('test').set({
testTitle: testTitle,
testText: testText
})
}
// etc
}
Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls. (If you’re curious, explanation available here)
According to you code samle I may suggest that testTitle, testText available in DataInput in some way, thus you may create onClick handler with useCallback. React will create callback for use as handler, and re-create only when testTitle, testText changed.
import {useCallback} from 'react';
export const DataInput = () => {
const makePost = useCallback(() => {
useFirestore().collection('schedule-data').doc('test').set({
testTitle: testTitle,
testText: testText
})
}, [testTitle, testText]);
return (
<Button
variant="primary"
onClick={makePost}
{/* Avoid inline callback declaration */}
>
POST data
</Button>
)
}

Why does React.useCallback trigger rerender, thouh it should not?

I have redux connected Component with onClick action bound to it. Every time I click it rerenders, though I use useCallback hook. Here is my simplified component:
const Map = props => {
const dispatch = useDispatch(); // from react-redux
const coordinates = useSelector(state => state.track.coordinates); // from react-redux
const onClick = useCallback( // from react
data => {
return dispatch({type: 'ADD_COORDINATES', payload: data});
},
[dispatch]
);
return (
<div className="Map">
<GoogleMap
onClick={onClick}>
<Track
coordinates={coordinates}
/>
</GoogleMap>
</div>
);
};
Without giving any additional context, and that the component is really "simplified" (there is nothing else that may cause a render), Map component will re-render only on its parent render:
const Parent = () => {
const coordinates = useSelector(coordinatesSelector);
return <Map />;
};
On dispatching addCoordinates action you may trigger its parent.
You should try and memoize the Map component:
If your function component renders the same result given the same props, you can wrap it in a call to React.memo for a performance boost in some cases by memoizing the result. This means that React will skip rendering the component, and reuse the last rendered result.
const Map = () => {
...
return ....;
};
export default React.memo(Map);
Edit after question update:
Your component re-renders due to useSelector as stated in the docs:
When an action is dispatched, useSelector() will do a reference comparison of the previous selector result value and the current result value. If they are different, the component will be forced to re-render. If they are the same, the component will not re-render.
Therefore, you might want to add additional equalityFn:
const coordinates = useSelector(state => state.track.coordinates, areSameCoords)

React - functions as props causing extra renders

I have some heavy forms that I'm dealing with. Thus, I'm trying to squeeze performance wherever I can find it. Recently I added the Why-did-you-render addon to get more insight on what might be slowing down my pages. I noticed that, for example, when I click on a checkbox component about all of my other components re-render. The justification is always the same. WDYR says
Re-rendered because of props changes: different functions with the
same name {prev onChangeHandler: ƒ} "!==" {next onChangeHandler: ƒ}
As much as possible, I try to respect best the best practices indications that I find. The callback functions that my component passes follow this pattern
import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
export function TopLevelComponent({props}){
const defaultData = {name: '', useMale: false, useFemale: false}
const [data, setData] = useState(defData);
const { t } = useTranslation();
const updateState = (_attr, _val) => {
const update = {};
update[_attr] = _val;
setData({ ...data, ...update });
}
const updateName = (_v) => updateState('name', _v);//Text input
const updateUseMale = (_v) => updateState('useMale', _v);//checkbox
const updateUseFemale = (_v) => updateState('useFemale', _v);//checkbox
...
return <div>
...
<SomeInputComponent value={data.name} text={t('fullName')} onChangeHandler={updateName} />
<SomeCheckboxComponent value={data.useMale} onChangeHandler={updateUseMale} text={t('useMale')}/>
<SomeCheckboxComponent value={data.useFemale} onChangeHandler={updateUseFemale} text={t('useFemale')}/>
...
</div>
}
In an example like this one, altering any of the inputs (eg: Writing text in the text input or clicking one of the checkboxes) would cause the other 2 components to re-render with the justification presented above.
I guess that I could stop using functional components and utilize the shouldComponentUpdate() function, but functional components do present some advantages that I'd rather keep. How should I write my functions in such a way that interacting with one input does not force an update on another input?
The problem stems from the way you define your change handlers:
const updateName = (_v) => updateState('name', _v)
This line is called on each render and thus, every time your component is rendered, the prop has a new (albeit functionality-wise identical) value. The same holds for every other handler as well.
As an easy solution you can either upgrade your functional component to a fully fledged component and cache the handlers outside of the render function, or you can implement shouldComponentUpdate() in your child components.
You need to use memo for your child components to reduce renders
const SomeInputComponent = props => {
};
export default memo(SomeInputComponent);
// if it still causes rerender witout any prop change then you can use callback to allow or block render
e.f.
function arePropsEqual(prevProps, nextProps) {
return prevProps.name === nextProps.name; // use your logic to determine if props are same or not
}
export default memo(SomeInputComponent, arePropsEqual);
/* One reason for re-render is that `onChange` callback passed to child components is new on each parent render which causes child components to re-render even if you use `momo` because function is updated on each render so in order to fix this, you can use React hook `useCallback` to get the same function reference on each render.
So in you parent component, you need to do something like
*/
import { useCallback } from 'react';
const updateName = useCallback((_v) => updateState('name', _v), [])
You have to memoize parent function before pass to children, using useCallback for functional component or converting to class property if you use class.
export default class Parent extends React.PureComponent {
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
}
onClick() {
console.log("click");
}
render() {
return (
<ChildComponent
onClick={ this.onClick }
/>
);
}
}
with useCallback:
Parent = () => {
const onClick = useCallback(
() => console.log('click'),
[]
);
return (
<ChildComponent
onClick={onClick}
/>
);
}

Categories