Tuesday 8 October 2019

react hooks createContext

useContext enables sharing state between multiple components without explicitly passing a prop through every level of the tree.

part initially named screw, 
part name and function to change name are stored in context created at top level.
they are accessible to lower levels
when part name is changed at any level, part name on other level auto updated as well
no passing props from top down required





//Top

import React, { createContext, useState } from "react";
import SubAssembly from './Sub'

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

function TopAssembly() {
  // Use the Provider to make a value available to all
  // children and grandchildren
  const [partName, setPartName] = useState('screw ')

  return (
    <partContext.Provider value={{ partName, setPartName }}>
      <div>
        Top Assembly <button onClick={() => setPartName('screw A ')}>update part on top level</button>
        <ul>
          <li>sub Assembly x</li>
          <li>sub Assembly y</li>
          <li><SubAssembly /></li>
        </ul>
      </div>
    </partContext.Provider>
  );
}

export default TopAssembly

------------------------------------
//Sub

import React, {useContext } from "react";
import {partContext} from './Top'
import BaseAssembly from './Base'

function SubAssembly() {

    const { setPartName } = useContext(partContext);
    return <div>Sub Assembly z <button onClick={() => setPartName('screw B ')}>update part at sub level</button>
      <ul>
        <li>base Assembly z1</li>
        <li>base Assembly z2</li>
        <li> <BaseAssembly /></li>
      </ul>
    </div>;
  }

  export default SubAssembly;

-----------------------------
//Base

import React, { useContext } from "react";
import { partContext } from './Top'

function BaseAssembly() {
    const { partName, setPartName } = useContext(partContext);
    return <div>Base Assembly z3 <button onClick={() => setPartName('screw C ')}>update part at base level</button>
        <ul>
            <li>nut</li>
            <li>washer</li>
            <li><span style={{ backgroundColor: 'black', color: 'white' }}>{partName}</span></li>
        </ul>
    </div>
}

export default BaseAssembly;

reference:
https://daveceddia.com/usecontext-hook/
https://www.codementor.io/sambhavgore/an-example-use-context-and-hooks-to-share-state-between-different-components-sgop6lnrd

No comments:

Post a Comment