Skip to main content

Command Palette

Search for a command to run...

How to use React Context like a pro

Updated
1 min readView as Markdown
How to use React Context like a pro

In this example , we need to extract the object directly from the value of ThemeContext.Provider Line11/ App.js Component by implementing a curly braces directly in our Function parameter Three.js / Line13

App.js

import React, { useState} from 'react';
import ThemeContext from './Context/ThemeContext';

class App extends React.Component {

    state = {
        theme :  ' dark '
     }

render() {
    return (

//line 10
        <ThemeContext.Provider  value= {{  ' theme ' :  this.state.theme  }} >
               <div>Hi From App</div>
          </ThemeContext.Provider>
  }

}

export default App;

=========================================

NOT EXTRACTED DIRECTLY

Two.js

import React, { useState} from 'react';
import ThemeContext from './Context/ThemeContext';


function Two() {

    return (
        <ThemeContext.Consumer>

 // line 12
           {( lol ) => <>
              <h2> lol.theme</h2>
                 </>
            }
       </ThemeContext.Consumer>
       );

}

export default Two ;

OR

EXTRACTED DIRECTLY

Three.js

import React, { useState} from 'react';
import ThemeContext from './Context/ThemeContext';


function Two() {

    return (
        <ThemeContext.Consumer>

   // we extract the object directly here
  // line 12
         {( { theme } ) => <>
              <h2> theme </h2>
                 </>
            }
       </ThemeContext.Consumer>
       );

}

export default Two ;
D

Thanks for explanation 👍

More from this blog

Omar's blog

135 posts