rbi-learning / Today-I-Learned

1 stars 0 forks source link

09/01 Day26 Official Notes #173

Open fhern077 opened 4 years ago

fhern077 commented 4 years ago

Context API

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

It's an alternative to prop drilling and allows us to have state shared between "siblings" react components that sit at the same level.

Context allows us to separate components from state allowing more components to focus on the view logic and makes state management centralized.


/*  Creates a Context object. When React renders a component that 
*   subscribes to this Context object it will read the current context 
*.  value from the closest matching Provider above it in the tree.
*/

const ButtonCounterContext = React.createContext(defaultValue);

# Every Context object comes with a Provider React component that allows consuming components to subscribe to context changes.
<ButtonCounterContext.Provider value={/* some value */}>

What we can do is move state, effects and hooks outside of a component in a manner in which we can share them across the application.

In order to expose context to different parts of the application we must expose these values in the provider In this example Imagine we want a way to record buttonClicks across the entire application

Another Context Example


// context/ButtonCounterContext
import React from "react";
const ButtonCounterContext = React.createContext();

ButtonCounterContextProvider = ({ children }) => {
    const [buttonClicks, setButtonClicks]= React.useState(0);
     return (
    <ButtonCounterContext.Provider
      value={{
        buttonClicks,
        setButtonClicks,
      }}
    >
      {children}
    </ButtonCounterContext.Provider>
     )
}

export { ButtonCounterContext, ButtonCounterContextProvider }

// App.js
const App = () => {

return (
    <ButtonCounterContextProvider>
        <OneButton/>
        <DisplayButtonCounts />
     </ButtonCounterContextProvider>
 );
}

// OneButton.js
import React from "react";

const OneButton =()=> {
   const { buttonClicks, setButtonClicks } = React.useContext(ButtonCounterContext);
   return(
     <button onClick={setButtonClicks(buttonClicks+1)}> Click Me</button>
   )
}

// DisplayButtonCounts
import React from "react";

const DisplayButtonCounts =()=> {
  const { buttonClicks } = React.useContext(ButtonCounterContext);
  return(
    <h1>{buttonClicks} </h1>
  )
}