Created
May 17, 2024 02:56
-
-
Save junxdev/2171edd6e6b0c004110b8270058b664e to your computer and use it in GitHub Desktop.
The cases when React components rerender when it uses Context or Children Props...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { createContext, useContext, useState } from "react"; | |
| const Context = createContext(1); | |
| function ChildrenPropsWithContext() { | |
| const level = useContext(Context); | |
| console.log("ChildrenPropsWithContext"); // prints when the context updates | |
| return <div>with context {level}</div>; | |
| } | |
| function ChildrenPropsWithoutContext() { | |
| console.log("ChildrenPropsWithoutContext"); // doesn't print when the context updates | |
| return <div>no context</div>; | |
| } | |
| function Children() { | |
| console.log("Children"); // prints when the state updates | |
| return <div>children</div>; | |
| } | |
| const Foo = () => { | |
| console.log("hello world"); // doesn't print because it's not rendered(= not in the tree) | |
| return <div />; | |
| }; | |
| function Parent({ children }) { | |
| const [state, setState] = useState(0); | |
| const foo = <Foo />; // not rendered | |
| console.log("Parent"); // prints when the state updates | |
| return ( | |
| <Context.Provider value={state}> | |
| <Children /> | |
| {children} | |
| <button onClick={() => setState(state + 1)}>+</button> | |
| </Context.Provider> | |
| ); | |
| } | |
| function App() { | |
| console.log("App"); // prints once when the app starts | |
| return ( | |
| <Parent> | |
| <ChildrenPropsWithContext /> | |
| <ChildrenPropsWithoutContext /> | |
| </Parent> | |
| ); | |
| } | |
| export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment