Context API

Version 01. basic

import React, { createContext } from 'react'

const Context = createContext()
const { Provider, Consumer: ApplicationConsumer } = Context


class ApplicationContextProvider extends React.Component {
    state = {
        color: 'blue'
    }

    actions = {
        setColor: (color) => {
            this.setState({ ...this.state, color })
        }
    }
    render() {
        const { state, actions, props: { children } } = this

        return (
            <Provider value={{ state, actions }}>
                {children}
            </Provider>
        )
    }
}

export {
    ApplicationConsumer,
    ApplicationContextProvider
}

version 02. HOC

version 03. Hooks

Last updated

Was this helpful?