score:23
In your case it doesn't really makes sense to memoize Child because if item changes, the child has to re-render. However if there is a case that props do not change , but still the child is re-rendering due to the functions getting recreated you would make use of useCallback
hook to memoize the functions, on each render. Also since you have memoized the handler, you should make use of the callback method to update state since item
inside the handler will only refer to the value it had when the function was initially created
function Parent() {
const [item, setItem] = useState({ name: "item", value: 0 });
const handleChangeItem = useCallback(() => {
setItem(prevItem => ({ ...prevItem, value: prevItem.value + 1 }));
}, []);
return (
<>
Name: {item.name} Value: {item.value}
<Child changeItem={handleChangeItem} />
</>
);
}
const Child = React.memo(function Child({ item, changeItem }) {
function handleClick() {
changeItem();
}
console.log("child render");
return (
<div>
<button onClick={handleClick}>change state in parent</button>
</div>
);
});
score:4
Shubham Khatri accurately answered the original question but I am adding this answer to point to the recommended way of avoiding this callback problem.
From the docs:
useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values. It also lets you optimize performance for components that trigger deep updates because you can pass dispatch down instead of callbacks.
From the FAQ:
In large component trees, an alternative we recommend is to pass down a dispatch function from useReducer via context...
https://reactjs.org/docs/hooks-faq.html#how-to-avoid-passing-callbacks-down
The key to all of this is that dispatch never changes, unlike callbacks which are created every render.
Source: stackoverflow.com
Related Query
- How to prevent child component from re-rendering when using React hooks and memo?
- How to reset child component from parent using React Context and Hooks
- Prevent react component from rendering twice when using redux with componentWillMount
- React 16: Call children's function from parent when using hooks and functional component
- How to prevent component from unmounting immediately when using React Router V4
- How to prevent React from re-rendering the whole component when using setInterval
- In React How to pass object using history.push from a component to child component and read data
- How to pass a json array that comes from backend to child component using props and react hooks?
- How to test side-effect when state hook is passed to a child component using React and jest?
- How to prevent a React component from unmounting when url path is matched using react-router-dom
- How to set state in parent from one child component and access the state in another child component using react and typescript?
- How do I use react context API to pass data from parent component to child component when using react-router in the parent component in React.js?
- How to send array of objects data from child component to parent component and store in the parent object using react hooks?
- How to pass an Array from Child component to Parent component using hooks in react
- How can I prevent my functional component from re-rendering with React memo or React hooks?
- How to pass the match when using render in Route component from react router (v4)
- CDN links for React packages and how to import it when using react using the scripts from CDN
- How to execute store.unsubscribe from useEffect using React hooks and Redux
- how and when to call a react component methods after state change from redux
- Getting the ref from a dynamic component when using Redux, React and react-router-dom 4.x
- Trigger child function from parent component using react hooks
- Rendering from a child to a parent using refs and portals in React
- How do I correctly add data from multiple endpoints called inside useEffect to the state object using React Hooks and Context API?
- How to update the correct state value in a parent component that gets its value from a child component using hooks in react?
- How to trigger an event in Parent Component from Child Component onClick() using React Hooks?
- React - How to prevent click event from child component
- react Portal - how to close modal when clicking outside of modal and how to assign ref to modal inside parent component rendering modal?
- Using React Hooks, when I pass down a prop from parent to a child component, the prop in the child component is undefined
- React How to change state value from child to Parent using useState and useContext
- How to pass function from FUNCTIONAL to CLASS component and access it outside of render( without prop ), using context in react js?
More Query from same tag
- How to do Batch Mutations with Apollo Client
- TypeError: Cannot read properties of undefined (reading 'requestContent')
- How do you route within a route in react
- FA Icon in placeholder of an input?
- Unable to get value of persisted state using redux-persist after the store is rehydrated
- (React rendering) SetInterval just keeps going faster and unpredictable
- Why does this React router NavLink either redirect or submit successfully but, not both?
- Clear values in number input in React
- How to pass a state to a Parent component if I have a button triggering the state in the 2nd Child in React
- Rendering a table from an array in react, best way to surround every five elements with a <tr>?
- How to convert beforeSend of ajax itno axios
- React component lifecycles still run after redirect
- Execute code from inline script that is fetched from another source
- Failed to compile node module when i try to export db from firebase
- How to paginate Firestore data in react?
- Convert class component to functional component in React
- Questions regarding pdf to image conversion with Node JS
- map function isn't returning the values
- React router 4 - Why is my component only rendered on manually setting the url but not on clicking a Link with same url?
- What is the best practice to use Oauth2, React, Node.js and Passport.js to authenticate user with Google sign on button?
- Material UI Slider and Typescript onChange number | number[] type
- Code is ginving suprising output in react. fucntion is not getting called after submit button
- D3 components overlapping with other React Components
- Need help to fetch API
- ckfinder showing message “cannot upload file” but still saving in folder
- How to templating json using Reactjs
- Weird behavior of React UseEffect with window click eventListener
- ReactJS - How does one delete a button component, that was just clicked?
- How to register an protocol/deep links to my Electron App?
- how do i import and use promise function on my react component?