## Notes - Changes in component **state** triggers a re-render - When a component re-renders, its descendants also re-render - The point of a re-render is to keep the UI in sync with React state ### Misconceptions - Components will change if **props** change - The entire app re-renders if state changes For the above, the opposite is true ## React Loop The core React loop is to check for any differences in the state, and re-render the UI in the event of any differences. ## Pure Components A **pure component** is one that *always* products the same UI when given the same props. The following is an impure component ```jsx function CurrentTime() { const now = new Date(); return ( <p>{now.toString()}</p> ) } ``` Can create a pure component via ```jsx function Decoration() { return ( <div className="decoration"> // Some icon here </div> ) } export default React.memo(Decoration); ``` By wrapping component with `React.memo()`, we tell React "I **know** what I'm doing; don't re--render this unless the props change" ## Context A pure component that consumes a context: ```jsx const GreetUser = React.memo(() => { const user = React.useContext(UserContext); if (!user) { return "Hi there!"; } return `Hello ${user.name}`; }) ``` If `user` state variable changes, a re-render will occur. It's similar to ```jsx const GreetUser = React.memo(({ user }) => { if (!user) { return "Hi there!"; } return `Hello ${user.name}`; }); ``` The re-render only happens in pure components that consume the `context`. ## References - [Why React Re-renders - Josh W Comeau](https://www.joshwcomeau.com/react/why-react-re-renders) - [[UI-UX MOC]] - [[ReactJS Study MOC]]