Preventing Rerender of Parent component in React

Hey All, This is my first post here. I'm building a project in React. I have a chat component, it has 2 subcomponents. I want to keep the messages state inside chat component. Subcomponents are: 1. Message List ( a components that takes in messages as props and lists them) 2. Input box ( a component that allows to add a new message to the messages array in the chat component. How do I prevent the chat component from rerendering when a new message is added and only allow the Message List component to rerender?
5 Replies
notdevkey
notdevkey17mo ago
is the re-render causing any trouble? because in most cases it's fine. the cleanest solution would probably be to create a React context and use the context only in the subcomponents, basically eliminating state from being attached to the main chat component
notdevkey
notdevkey17mo ago
React context still triggers re-renders in some specific cases when it's not needed, you can search it up, there's tools like useContextSelector to handle that, or for your case I think Zustand would be best https://github.com/pmndrs/zustand
GitHub
GitHub - pmndrs/zustand: 🐻 Bear necessities for state management in...
🐻 Bear necessities for state management in React. Contribute to pmndrs/zustand development by creating an account on GitHub.
notdevkey
notdevkey17mo ago
I really like Zustand for it's simplicity, and it solves the problem of unnecessary context re-renders
manavkush
manavkushOP17mo ago
Ohhh.... I just thought that this rerendering would cause the app to slow. Also if I wanted another child component like to show the chat info on top(like other user's name etc) then it'd also get rerendered due to the parent being rerendered. I'll try out the solutions you mentioned. Thanks !!! Also I read about React.Memo while searching for a solution. If I Memo on the parent component, then the parent wouldn't rerender unless the props passed to it changes right? So we can memoize that then only the child would rerender on state updates.
notdevkey
notdevkey17mo ago
that's true, but it kinda feels like forcing the component to not re-render, opposed by not re-rendering because it's physically not tied to a state it's not gonna slow anything down. it's good that you think about this to every single detail, but react was made to work this way so it's just fine
Want results from more Discord servers?
Add your server