Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { memo, useContext, useState } from 'react';
- /**
- * Nested context example
- * UPDATE FROM PREVIOUS EXAMPLE: we use 2 different contexts instead one and they are nested
- * BAD: children components that use inner context is re-rendered
- * when the outer context is updated even if it's not necessary
- */
- interface Count {
- value: number,
- }
- interface Random {
- value: number | null,
- }
- const CountContext = React.createContext<Count>({ value: 0 });
- const RandomContext = React.createContext<Random>({ value: null });
- /**
- * Main Smart Component
- * BAD: always rendered when Context changes since it updates a local state
- */
- export default function Demo2BContext() {
- console.log('App: render')
- const [count, setCount] = useState<Count>({ value: 0});
- const [random, setRandom] = useState<Random>({ value: 0.5});
- return (
- <CountContext.Provider value={count}>
- <RandomContext.Provider value={random}>
- <h1>Demo B: Context</h1>
- <button onClick={() => setCount({ value: count.value + 1})}>+</button>
- <button onClick={() => setCount({ value: count.value - 1})}>-</button>
- <button onClick={() => setRandom({ value: Math.random() })}>Random</button>
- <Dashboard />
- </RandomContext.Provider>
- </CountContext.Provider>
- );
- }
- // Middle Component
- // Never re-rendered because of memoization
- const Dashboard = React.memo(() => {
- console.log('dashboard: render')
- return <div>
- <CounterPanel />
- <RandomPanelMemo />
- </div>
- })
- // Child Component
- // BAD: Updated when any value of Context change: count / random or another (although memoized)
- const CounterPanel = React.memo(() => {
- const state = useContext(CountContext);
- console.log('CounterPanel: render')
- return <div>
- Count: {state.value}
- </div>
- })
- // Child Component
- // BAD: This is re-rendered even if counter is updated and todos is not
- function RandomPanel () {
- const state = useContext(RandomContext);
- console.log('RandomPanel: render')
- return <div>
- Random Value: {state.value}
- </div>
- }
- const RandomPanelMemo = memo(RandomPanel)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement