Skip to content

Instantly share code, notes, and snippets.

@edwintcloud
Last active June 20, 2019 17:44
Show Gist options
  • Save edwintcloud/93297f9de21ead19b9467a42ad5a6185 to your computer and use it in GitHub Desktop.
Save edwintcloud/93297f9de21ead19b9467a42ad5a6185 to your computer and use it in GitHub Desktop.
Context API Component
import React, { useState } from 'react';
export const Context = React.createContext(null);
export const ContextProvider = ({ initialState, children }) => {
const [state, setState] = useState(initialState);
const providerActions = {
setState: values =>
setState(prevState => {
return { ...prevState, ...values };
})
};
return (
<Context.Provider
value={{
state: { ...state },
...providerActions,
}}
>
{children}
</Context.Provider>
);
};
@edwintcloud
Copy link
Author

edwintcloud commented Jun 20, 2019

Example App.js wrapped with ContextProvider:

import React from 'react';
import { BrowserRouter, Route } from 'react-router-dom';
import routes from './routes';
import { ContextProvider } from './components';

export default props => {
  return (
    <BrowserRouter>
      <ContextProvider initialState={{ title: "Site Title" }}>
        {routes.map((route, i) => (
          <Route key={i} exact path={route.path} render={() => <route.component {...props} />} />
        ))}
      </ContextProvider>
    </BrowserRouter>
  );
};

Example of using Context in a component or page:

import React, { useContext } from 'react';
import { Context } from '../components';

export default props => {
  const context = useContext(Context);

  const handleClick = () => {
    context.setState({ title: "Changed Title" });
  };

  return (
    <div>
      <p>
        Welcome to {context.state.title}!
        <button onClick={handleClick}>Click me!</button>
      </p>
    </div>
  );
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment