Blogs

React hooks have been around for some time now, yet many React developers are not actively using them. I see two primary reasons behind this. The first reason is that many React developers are already involved in a large project, which requires a significant effort to migrate the entire codebase. The other reason is the familiarity with React Classes. With the experience, it feels more comfortable to keep using Classes. In this article, we’ll look into five reasons why you should consider React Hooks. **1. You don’t have to refactor a functional component into a class component when it grows** ## With React Hooks, since functional components have the capability of tapping into the state, the refactoring effort will be minimal. Let’s consider the below example, a dumb component that shows a label with a count. ``` export function ShowCount(props) { return ( <div> <h1> Count : {props.count} </h1> </div> ); } ``` Let’s say we need to increment the count with mouse clicks and let’s assume this only affects this particular component. As the first step, we need to introduce the state to our component. Let’s take a look at how we would do that with a class-based approach. ``` export class ShowCount extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } componentDidMount() { this.setState({ count: this.props.count }) } render() { return ( <div> <h1> Count : {this.state.count} </h1> </div> ); } } ``` ## 2. You don’t have to worry about “this” anymore Classes confuse both people and machines The above sentence is from React documentation. One of the reasons for this confusion is this keyword. If you are familiar with JavaScript, you know that this in JavaScript doesn’t work exactly like in other languages. When it comes to React Hooks, you don’t have to worry about this at all. This is good for beginners as well as experienced developers. Accessing state using Hooks vs Classes According to the above example, you can see that we no longer have to use “this” while accessing the state. This makes it less confusing for everyone. ## 3. No more method bindings Now for the above same ShowCount component let’s introduce a method to update the count of the state when the user clicks on the label. ``` export class ShowCount extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; this.handleClickEvent = this.handleClickEvent.bind(this); } componentDidMount() { this.setState({ count: this.props.count }); } handleClickEvent() { this.setState({count: this.state.count + 1}); } render() { return ( <div> <h1 onClick={this.handleClickEvent} > Count : {this.state.count} </h1> </div> ); } } ``` We have introduced handleClickEvent method. To use it, first, we have to bind it to this of the Component. We have to do this because the execution context is different when the method gets executed. For a beginner developer, this might be a bit hard to understand. Instead of binding all the methods, there are some syntax proposals where you can get around this. For example, we can rewrite the function to an arrow function. ``` handleClickEvent = () => { this.setState({count: this.state.count + 1}); } ``` Let’s see how we can implement the same functionality with Hooks. ``` export function ShowCount(props) { const [count, setCount] = useState(); useEffect(() => { setCount(props.count); }, [props.count]); function handleClickEvent() { setCount(count + 1); } return ( <div> <h1 onClick={handleClickEvent}> Count : {count} </h1> </div> ); } ``` As you can see, we have only added the function. Also, you might notice that when we use the event handler, we have removed this in the template. ``` onClick={ handleClickEvent } ``` ## 4. Easier to decouple logic from UI, making both more reusable Using hooks, logic and UI are easier to separate. No need for HOC or render props. Hooks do it elegantly with less boilerplate and more intuitive compositions of UI and logic. This “elegant separation” is especially crucial when sharing components using tools and platforms like Bit (Github) as each (independently shared) component is much easier to understand, maintain, and reuse across different apps. ## 5. Keep related logic in the same place Complex components become hard to understand With the class-based approach, we have different life cycle methods such as componentDidMountand componentDidUpdate etc. Let's consider a situation where subscribing to services A and B in componentDidMount and unsubscribing them on componentWillUnmount. With time, there will be many logics included in both life cycle methods, and it will be hard to keep track of which part of mounting is related in unmounting. To demonstrate this, let's create an RxJs based service to get the count. We will use this service to update the count in ShowCount example. Note that we will be removing the handleClickEvent as we no longer need to update the component on click events. ``` import { Subject } from "rxjs"; export function getCounts() { const subject = new Subject(); let count = 0; const interval = setInterval(() => { if (count > 10 || subject.isStopped) { clearInterval(interval); subject.complete(); } subject.next(count++); }, 1000); return subject; } ``` ``` export function ShowCount(props) { const [count, setCount] = useState(); useEffect(() => { const countServiceSubject = getCounts(); countServiceSubject.subscribe((count) => { setCount(count); }); return () => { countServiceSubject.unsubscribe(); }; }, []); return ( <div> <h1> Count : {count} </h1> </div> ); } ``` ShowCount component with getCounts method in Effect Hook You can see that inside the useEffect we have included subscribing as well as corresponding unsubscribing logic. Similarly, if we need to introduce more service subscriptions or unrelated logics, we can add multiple useEffect blocks to logically separate different concerns. ``` export function ShowCount(props) { const [count, setCount] = useState(); const [secondCount, setSecondCount] = useState(0); useEffect(() => { const countServiceSubject = getCounts(); countServiceSubject.subscribe((count) => { setCount(count); }); return () => { countServiceSubject.unsubscribe(); }; }, []); useEffect(() => { setSecondCount(secondCount + 1); }, []); return ( <div> <h1> Count : {count} </h1> <h1> Second Count: {secondCount} </h1> </div> ); } ```

Continue Reading ...

## Introduction Strapi is a headless content management system (CMS) built with React.js and Node.js. It is easy to learn. It supports PostgreSQL, MongoDB, SQLite, MySQL and MariaDB. You can work with any of the above-mentioned databases to build your next big Strapi project. ## Strapi Plugins Strapi has a very unique yet powerful design pattern that lets you build almost anything. It has a plugin design pattern. You can think of plugins in Strapi as smaller applications with unique functionalities that are injected into the main project. It would help to think of a single Strapi plugin as a house in a housing estate. The Strapi app is the housing estate. A Strapi application can be expanded beyond the scope of its core features with the power of plugins. Remember when we talked about React.js and Node.js? You will need a background knowledge of those to be able to build upon Strapi. React and Node are the main technologies used in Strapi and have grown so much in popularity recently. You can get started looking at their respective documentations if you are not familiar with them. The scope of this tutorial would not cover the essentials of Node and React. I will assume you already know the basics ## Plugin Structure Remember how we described Strapi plugins as individual apps all within the main Strapi application. The part of the plugin that shows up on the Strapi dashboard is built with React.js components. These components are in plugin→admin→src→components. The image below further explains the folder structure of a Strapi plugin. ``` plugin/ └─── admin/ # Contains the plugin's front-end | └─── src/ # Source code directory | └─── index.js # Entry point of the plugin | └─── pluginId.js # Name of the plugin | | | └─── components/ # Contains the list of React components used by the plugin | └─── containers/ | | └─── App/ # Container used by every other container | | └─── Initializer/ # This container is required. It is used to executed logic right after the plugin is mounted. | └─── translations/ # Contains the translations to make the plugin internationalized | └─── en.json | └─── index.js # File that exports all the plugins translations. | └─── fr.json └─── config/ # Contains the configurations of the plugin | └─── functions/ | | └─── bootstrap.js # Asynchronous bootstrap function that runs before the app gets started | └─── policies/ # Folder containing the plugin's policies | └─── queries/ # Folder containing the plugin's models queries | └─── routes.json # Contains the plugin's API routes └─── controllers/ # Contains the plugin's API controllers └─── middlewares/ # Contains the plugin's middlewares └─── models/ # Contains the plugin's API models └─── services/ # Contains the plugin's API services ``` ## Install Strapi Let's get started by installing Strapi using the following command: ``` yarn create strapi-app my-plugin-project --quickstart ``` Using the quickstart command instructs Strapi to select all the necessary options and speeds up the installation process. Once the installation is completed, our project will be launched in the browser prompting us to create the first admin account. Go ahead and create your admin account by providing the necessary details. Then create a few collections in the Strapi dashboard too. Look up the official documentation if you need help creating collections. ## Create our plugin To create our plugin, we will use the following Yarn command. ``` yarn strapi generate:plugin customPlugin ``` After generating our plugin, Notice the similarity in the folder structure with what we have in the plugin structure above. There is an index.js file at the root of the admin folder all within the plugins folder. The file contains the following: ``` import pluginPkg from '../../package.json'; import pluginId from './pluginId'; import App from './containers/App'; import Initializer from './containers/Initializer'; import lifecycles from './lifecycles'; import trads from './translations'; export default strapi => { const pluginDescription = pluginPkg.strapi.description || pluginPkg.description; const icon = pluginPkg.strapi.icon; const name = pluginPkg.strapi.name; const plugin = { blockerComponent: null, blockerComponentProps: {}, description: pluginDescription, icon, id: pluginId, initializer: Initializer, injectedComponents: [], isReady: false, isRequired: pluginPkg.strapi.required || false, layout: null, lifecycles, mainComponent: App, name, preventComponentRendering: false, trads, menu: { pluginsSectionLinks: [ { destination: `/plugins/${pluginId}`, icon, label: { id: `${pluginId}.plugin.name`, defaultMessage: name, }, name, permissions: [ // Uncomment to set the permissions of the plugin here // { // action: '', // the action name should be plugins::plugin-name.actionType // subject: null, // }, ], }, ], }, }; return strapi.registerPlugin(plugin); }; ``` Notice the pluginsSectionLinks method, it displays the icon of our plugin and mainComponent displays what we have in the App component in the component page. The App component can be found in the **containers/HomePage/index.js** directory Restart the development server with the following command: ``` yarn develop --watch-admin ``` Edit the index.js file and add the following lines of code to it: ``` const HomePage = () => { return ( <div> <h1>I changed my title</h1> <p>Hi! I just earned my self a bragging right for chaning the title of this plugin</p> </div> ); }; ```

Continue Reading ...

As an introduction of style-components I as that styled-components is a massively growing community around with over 22,000 on GitHub, mostly coming from React developers, which is very encouraging and speaks to the prospects of longevity. Styled components are a CSS-in-JS tool that bridges the gap between components and styling, offering numerous features to get you up and running in styling components in a functional and reusable way. In this article, you’ll learn the basics of styled components and how to properly apply them to your React applications. ### Reasons to use styled-components: ### Performance improvements Styled components keep track of which components are rendered on a given page and inject their styles and nothing else. This means your user loads the least amount of styles necessary for a given component. ### Reusable components Styled components allow us to create components that are extremely easy to reuse as they directly contain their style values. #### Some of the following JSX: ``` <h1 className="title" > G Soft </h1> ``` #### can be translated in the following component: ``` const Title=styled.h1` color:white; font-size:3rem; ` ``` #### And ca be used like so: ``` <Title>G Soft<Title> ``` ## No -class policy: Styled-components enforces the use of props in the place of classes. This no-class policy has helped them make more developers tow the route of best practices for controlling the behavior of a component. #### Initially, you would write: ``` <h2 className="title primary"> Hello world </h2> h2.Subtitle{ font-size : 2em; color : green; &.primary{ color : red; } } ``` #### but now , it should be like this: ``` const Subtitle= styled.h2` font-size : 2em; color : ${ props=>props.primary ? 'red' : 'green' }; `; <Subtitle primary> Hello World <Subtitle> ```

Continue Reading ...