React Context 101

Thought of putting out something short as a way to practice my writing. I wrote this without research or much planning, but I hope it will help someone out there.

Have you worked with a React app that needed the same data in multiple components? If you have worked with something larger than a to-do app, the odds are yes, you have. How would you pass down the data? Store the data higher up in React state and pass them down to child components (and sometimes their children) via props? Reach out to Redux (or Mobx etc.)? Or do you have some other way? React has now introduced something in core that you can make use of. It’s called React Context.

Context has two main parts:

  1. Provider – where the data is fed.
  2. Consumer – where the data is used.

Creating a React Context

To create a context, you have to use the React.createContext method:

export  const  CartContext  =  new  React.createContext({});

In the above code sample, we are creating a context. We can pass default values as arguments if we want. In this case, I’m just passing an empty object.

Using the Context

We have to wrap the parent component or any component above it within CartContext.Provider in order to use the data inside a child component:

<CartContext.Provider  value={{ itemCount:  2 }}>
	<Cart  />
</CartContext.Provider>

In the above sample, we are passing a value for the property itemCount as 2.

Let’s see how to consume the itemCount inside of the Cart component or even inside of its child:

const  Cart  =  ()  =>  {
 const  cartData  =  React.useContext(CartContext);
 return  (
   <div>
	<h2>Cart</h2>
	{cartData.itemCount}
   </div>
 );
};

That would display 2 inside the Child component! We also just used React Hooks (useContext), congratulations!

Thinking in WordPress

WordPress is a handy blogging tool, a useful Content Management System or a capable web application framework. Whatever way you look at it, WordPress helps you solve problems in creative ways. In this article, I want to talk about how I approach projects and my methodology for problem-solving with WordPress. This is not an exhaustive list and one article wouldn’t do justice to the vastness of WordPress. I will try to add whatever pointers stand out among the decisions you would probably have to take.

Thinking in the woods?
Continue reading “Thinking in WordPress”

My Favorite WordPress Features

As you work with WordPress for some time, you begin to realize WordPress is much more than a blogging tool. Sometimes, even more than a regular CMS. In this post, I will talk about the different features/add-ons of WordPress and how you can utilize them for your next problem or project. Specifically, this post comes from my experience with WordPress and what I love about the different WordPress features.

Continue reading “My Favorite WordPress Features”