-3

I completed some tutorials but still not catch it. I have these problems: where to use it, how it works (with example).

oddball8
  • 368
  • 2
  • 5
  • 19
Leart Morina
  • 56
  • 1
  • 8
  • Possible duplicate of [React Context vs React Redux, when should I use each one?](https://stackoverflow.com/questions/49568073/react-context-vs-react-redux-when-should-i-use-each-one) – Ajay Varghese Jun 20 '19 at 12:00

1 Answers1

0

Context is used in cases where you want to share some global state with multiple components. You set up an initial state that you then pass as a value to the Context Provider. The Context Provider wraps all the children components that you wish to have access to that state.

It can be use in various situations. Here's a basic and silly example:

You want to use the same color for all your buttons in your web app. You can use context to pass that color to all the children components. If you need to change the color for all your buttons you change it only in one place.

Example:

//App.js

// Create a Context
export const ColorContext = React.createContext();
// It returns an object with 2 values:
// { Provider, Consumer }

//set up an initial state
let initialState = {color: 'red'};

function App() {
  // Use the Provider to make a value available to all
  // children and grandchildren
  return (
    <ColorContext.Provider value={initialState}>
      <div>
        <Display />
      </div>
    </ColorContext.Provider>
  );
}

//Child Component
//import useContext and the context variable defined in App.js
import React, { useContext } from 'react';
import { ColorContext } from './App.js';
// ...

function Display() {
  const value = useContext(ColorContext);
  return <div style={{ color: value.color }}>The color is {value.color}.</div>;
}
Ovidiu G
  • 1,033
  • 5
  • 18
  • 40