React Redux Cheat Sheet



The react-redux package, the official Redux-UI binding package for React, lets your React components interact with a Redux store without writing the interaction logic yourself. This allows an application to rely on Redux to manage the global state and React to render the UI based on the state. Interactions may include reading data from a Redux store and dispatching actions to the store. Title: VSCode ES7 React/Redux snippets Cheat Sheet by frankieali4 - Cheatography.com Created Date: 5943Z. Reducers are a powerful pattern for managing state that is used in the popular state management library Redux (commonly used with React). Reducers can be used in React with the useReducer hook in order to manage state across our app, as compared to useState (which is for local component state). React awesome-redux Awesome Redux enzyme Enzyme enzyme@2 Enzyme v2 flux Flux architecture react-router React-router react React.js react@0.14 React.js (v0.14) redux Redux Ruby activeadmin ActiveAdmin bundler Bundler goby Goby minitest Minitest rake Rake rbenv rbenv rspec-rails Rspec-rails rspec RSpec ruby Ruby ruby21 Ruby 2.1 rubygems Rubygems. Download your iJS React Cheat Sheet and understand all important functions of the JavaScript library! Download your iJS React Cheat Sheet and understand all important functions of the JavaScript library! Real-world advanced Redux patterns →.

Most of the React Native styling material in one page. Imported from the official docs.

Contents

General

Components

Flexbox

NameTypeDescription
alignItemsoneOfflex-start, flex-end, center, stretchalignItems aligns children in the cross direction. For example, if children are flowing vertically, alignItems controls how they align horizontally. It works like align-items in CSS, except the default value is stretch instead of flex-start. See https://css-tricks.com/almanac/properties/a/align-items/ for more detail.
alignSelfoneOfauto, flex-start, flex-end, center, stretchcontrols how a child aligns in the cross direction, overriding the alignItems of the parent. It works like align-self in CSS. See https://css-tricks.com/almanac/properties/a/align-self/ for more detail.
borderBottomWidthnumberborderBottomWidth works like border-bottom-width in CSS. See http://www.w3schools.com/cssref/pr_border-bottom_width.asp for more details.
borderLeftWidthnumberborderLeftWidth works like border-left-width in CSS. See http://www.w3schools.com/cssref/pr_border-bottom_width.asp for more details.
borderRightWidthnumberborderRightWidth works like border-right-width in CSS. See http://www.w3schools.com/cssref/pr_border-right_width.asp for more details.
borderTopWidthnumberborderTopWidth works like border-top-width in CSS. See http://www.w3schools.com/cssref/pr_border-top_width.asp for more details.
borderWidthnumberborderWidth works like border-width in CSS. See http://www.w3schools.com/cssref/pr_border-width.asp for more details.
bottomnumberbottom is the number of logical pixels to offset the bottom edge of this component. It works similarly to bottom in CSS, but in React Native you must use logical pixel units, rather than percents, ems, or any of that. See https://developer.mozilla.org/en-US/docs/Web/CSS/bottom for more details of how top affects layout.
flexnumberIn React Native flex does not work the same way that it does in CSS. flex is a number rather than a string, and it works according to the css-layout library at https://github.com/facebook/css-layout . When flex is a positive number, it makes the component flexible and it will be sized proportional to its flex value. So a component with flex set to 2 will take twice the space as a component with flex set to 1. When flex is 0, the component is sized according to width and height and it is inflexible. When flex is -1, the component is normally sized according width and height. However, if there’s not enough space, the component will shrink to its minWidth and minHeight.
flexDirectiononeOfrow, row-reverse, column, column-reverseflexDirection controls which directions children of a container go. row goes left to right, column goes top to bottom, and you may be able to guess what the other two do. It works like flex-direction in CSS, except the default is column. See https://css-tricks.com/almanac/properties/f/flex-direction/ for more detail.
flexWraponeOfwrap, nowrapflexWrap controls whether children can wrap around after they hit the end of a flex container. It works like flex-wrap in CSS. See https://css-tricks.com/almanac/properties/f/flex-wrap/ for more detail.
heightnumberheight sets the height of this component. It works similarly to height in CSS, but in React Native you must use logical pixel units, rather than percents, ems, or any of that. See http://www.w3schools.com/cssref/pr_dim_width.asp for more details.
justifyContentoneOfflex-start, flex-end, center, space-between, space-aroundjustifyContent aligns children in the main direction. For example, if children are flowing vertically, justifyContent controls how they align vertically. It works like justify-content in CSS. See https://css-tricks.com/almanac/properties/j/justify-content/ for more detail.
leftnumberleft is the number of logical pixels to offset the left edge of this component. It works similarly to left in CSS, but in React Native you must use logical pixel units, rather than percents, ems, or any of that. See https://developer.mozilla.org/en-US/docs/Web/CSS/left for more details of how left affects layout.
marginnumberSetting margin has the same effect as setting each of marginTop, marginLeft, marginBottom, and marginRight.
marginBottomnumbermarginBottom works like margin-bottom in CSS. See http://www.w3schools.com/cssref/pr_margin-bottom.asp for more details.
marginHorizontalnumberSetting marginHorizontal has the same effect as setting both marginLeft and marginRight.
marginLeftnumbermarginLeft works like margin-left in CSS. See http://www.w3schools.com/cssref/pr_margin-left.asp for more details.
marginRightnumbermarginRight works like margin-right in CSS. See http://www.w3schools.com/cssref/pr_margin-right.asp for more details.
marginTopnumbermarginTop works like margin-top in CSS. See http://www.w3schools.com/cssref/pr_margin-top.asp for more details.
marginVerticalnumberSetting marginVertical has the same effect as setting both marginTop and marginBottom.
maxHeightnumbermaxHeight is the maximum height for this component, in logical pixels. It works similarly to max-height in CSS, but in React Native you must use logical pixel units, rather than percents, ems, or any of that. See http://www.w3schools.com/cssref/pr_dim_max-height.asp for more details.
maxWidthnumbermaxWidth is the maximum width for this component, in logical pixels. It works similarly to max-width in CSS, but in React Native you must use logical pixel units, rather than percents, ems, or any of that. See http://www.w3schools.com/cssref/pr_dim_max-width.asp for more details.
minHeightnumberminHeight is the minimum height for this component, in logical pixels. It works similarly to min-height in CSS, but in React Native you must use logical pixel units, rather than percents, ems, or any of that. See http://www.w3schools.com/cssref/pr_dim_min-height.asp for more details.
minWidthnumberminWidth is the minimum width for this component, in logical pixels. It works similarly to min-width in CSS, but in React Native you must use logical pixel units, rather than percents, ems, or any of that. See http://www.w3schools.com/cssref/pr_dim_min-width.asp for more details.
paddingnumberpadding works like padding in CSS. It’s like setting each of paddingTop, paddingBottom, paddingLeft, and paddingRight to the same thing. See http://www.w3schools.com/css/css_padding.asp for more details.
paddingBottomnumberpaddingBottom works like padding-bottom in CSS. See http://www.w3schools.com/cssref/pr_padding-bottom.asp for more details.
paddingHorizontalnumberSetting paddingHorizontal is like setting both of paddingLeft and paddingRight.
paddingLeftnumberpaddingLeft works like padding-left in CSS. See http://www.w3schools.com/cssref/pr_padding-left.asp for more details.
paddingRightnumberpaddingRight works like padding-right in CSS. See http://www.w3schools.com/cssref/pr_padding-right.asp for more details.
paddingTopnumberpaddingTop works like padding-top in CSS. See http://www.w3schools.com/cssref/pr_padding-top.asp for more details.
paddingVerticalnumberSetting paddingVertical is like setting both of paddingTop and paddingBottom.
positiononeOfabsolute, relativeposition in React Native is similar to regular CSS, but everything is set to relative by default, so absolute positioning is always just relative to the parent. If you want to position a child using specific numbers of logical pixels relative to its parent, set the child to have absolute position. If you want to position a child relative to something that is not its parent, just don’t use styles for that. Use the component tree. See https://github.com/facebook/css-layout for more details on how position differs between React Native and CSS.
rightnumberright is the number of logical pixels to offset the right edge of this component. It works similarly to right in CSS, but in React Native you must use logical pixel units, rather than percents, ems, or any of that. See https://developer.mozilla.org/en-US/docs/Web/CSS/right for more details of how right affects layout.
topnumbertop is the number of logical pixels to offset the top edge of this component. It works similarly to top in CSS, but in React Native you must use logical pixel units, rather than percents, ems, or any of that. See https://developer.mozilla.org/en-US/docs/Web/CSS/top for more details of how top affects layout.
widthnumberwidth sets the width of this component. It works similarly to width in CSS, but in React Native you must use logical pixel units, rather than percents, ems, or any of that. See http://www.w3schools.com/cssref/pr_dim_width.asp for more details.
zIndexnumberzIndex controls which components display on top of others. Normally, you don’t use zIndex. Components render according to their order in the document tree, so later components draw over earlier ones. zIndex may be useful if you have animations or custom modal interfaces where you don’t want this behavior. It works like the CSS z-index property - components with a larger zIndex will render on top. Think of the z-direction like it’s pointing from the phone into your eyeball. See https://developer.mozilla.org/en-US/docs/Web/CSS/z-index for more detail.

Shadow Prop Types IOS

NameTypeDescription
shadowColorcustomColorPropTypeSets the drop shadow color
shadowOffsetcustomReactPropTypes.shape( {width: ReactPropTypes.number, height: ReactPropTypes.number} )Sets the drop shadow offset
shadowOpacitynumberSets the drop shadow opacity (multiplied by the color’s alpha component)
shadowRadiusnumberSets the drop shadow blur radius

Transforms

NameType
decomposedMatrixcustomDecomposedMatrixPropType
transformcustomReactPropTypes.arrayOf( ReactPropTypes.oneOfType([ ReactPropTypes.shape({perspective: ReactPropTypes.number}), ReactPropTypes.shape({rotate: ReactPropTypes.string}), ReactPropTypes.shape({rotateX: ReactPropTypes.string}), ReactPropTypes.shape({rotateY: ReactPropTypes.string}), ReactPropTypes.shape({rotateZ: ReactPropTypes.string}), ReactPropTypes.shape({scale: ReactPropTypes.number}), ReactPropTypes.shape({scaleX: ReactPropTypes.number}), ReactPropTypes.shape({scaleY: ReactPropTypes.number}), ReactPropTypes.shape({translateX: ReactPropTypes.number}), ReactPropTypes.shape({translateY: ReactPropTypes.number}), ReactPropTypes.shape({skewX: ReactPropTypes.string}), ReactPropTypes.shape({skewY: ReactPropTypes.string}) ]) )
transformMatrixcustomTransformMatrixPropType

Image

NameRequiredTypePlatformsDescription
…Flexbox
…ShadowPropTypesIOS
…Transforms
backfaceVisibilityfalseoneOfvisible, hidden
backgroundColorfalseColorPropType
borderBottomLeftRadiusfalsenumber
borderBottomRightRadiusfalsenumber
borderColorfalseColorPropType
borderRadiusfalsenumber
borderTopLeftRadiusfalsenumber
borderTopRightRadiusfalsenumber
borderWidthfalsenumber
opacityfalsenumber
overflowfalseoneOfvisible, hidden
resizeModefalseoneOfObject.keys(ImageResizeMode))
tintColorfalseColorPropTypeChanges the color of all the non-transparent pixels to the tintColor.
overlayColorfalsestringandroidWhen the image has rounded corners, specifying an overlayColor will cause the remaining space in the corners to be filled with a solid color. This is useful in cases which are not supported by the Android implementation of rounded corners: - Certain resize modes, such as ‘contain’ - Animated GIFs A typical way to use this prop is with images displayed on a solid background and setting the overlayColor to the same color as the background. For details of how this works under the hood, see http://frescolib.org/docs/rounded-corners-and-circles.html

ScrollView

NameRequiredTypePlatformsDescription
…Flexbox
…ShadowPropTypesIOS
…Transforms
backfaceVisibilityfalseoneOfvisible, hidden
backgroundColorfalseColorPropType
borderBottomColorfalseColorPropType
borderBottomLeftRadiusfalsenumber
borderBottomRightRadiusfalsenumber
borderBottomWidthfalsenumber
borderColorfalseColorPropType
borderLeftColorfalseColorPropType
borderLeftWidthfalsenumber
borderRadiusfalsenumber
borderRightColorfalseColorPropType
borderRightWidthfalsenumber
borderStylefalseoneOfsolid, dotted, dashed
borderTopColorfalseColorPropType
borderTopLeftRadiusfalsenumber
borderTopRightRadiusfalsenumber
borderTopWidthfalsenumber
borderWidthfalsenumber
opacityfalsenumber
overflowfalseoneOfvisible, hidden
elevationfalsenumberandroid(Android-only) Sets the elevation of a view, using Android’s underlying elevation API. This adds a drop shadow to the item and affects z-order for overlapping views. Only supported on Android 5.0+, has no effect on earlier versions.

Text

NameRequiredTypePlatformsDescription
…View
colorfalseColorPropType
fontFamilyfalsestring
fontSizefalsenumber
fontStylefalseoneOfnormal, italic
fontWeightfalseoneOfnormal, bold, 100, 200, 300, 400, 500, 600, 700, 800, 900Specifies font weight. The values ‘normal’ and ‘bold’ are supported for most fonts. Not all fonts have a variant for each of the numeric values, in that case the closest one is chosen.
lineHeightfalsenumber
textAlignfalseoneOfauto, left, right, center, justifySpecifies text alignment. The value ‘justify’ is only supported on iOS and fallbacks to left on Android.
textDecorationLinefalseoneOfnone, underline, line-through, underline, line-through
textShadowColorfalseColorPropType
textShadowOffsetfalseReactPropTypes.shape( {width: ReactPropTypes.number, height: ReactPropTypes.number} )
textShadowRadiusfalsenumber
textAlignVerticalfalseoneOfauto, top, bottom, centerandroid
letterSpacingfalsenumberios
textDecorationColorfalseColorPropTypeios
textDecorationStylefalseoneOfsolid, double, dotted, dashedios
writingDirectionfalseoneOfauto, ltr, rtlios
React

View

NameRequiredTypePlatformsDescription
…Flexbox
…ShadowPropTypesIOS
…Transforms
backfaceVisibilityfalseoneOfvisible, hidden
backgroundColorfalseColorPropType
borderBottomColorfalseColorPropType
borderBottomLeftRadiusfalsenumber
borderBottomRightRadiusfalsenumber
borderBottomWidthfalsenumber
borderColorfalseColorPropType
borderLeftColorfalseColorPropType
borderLeftWidthfalsenumber
borderRadiusfalsenumber
borderRightColorfalseColorPropType
borderRightWidthfalsenumber
borderStylefalseoneOfsolid, dotted, dashed
borderTopColorfalseColorPropType
borderTopLeftRadiusfalsenumber
borderTopRightRadiusfalsenumber
borderTopWidthfalsenumber
borderWidthfalsenumber
opacityfalsenumber
overflowfalseoneOfvisible, hidden
elevationfalsenumberandroid(Android-only) Sets the elevation of a view, using Android’s underlying elevation API. This adds a drop shadow to the item and affects z-order for overlapping views. Only supported on Android 5.0+, has no effect on earlier versions.

Appendix

Types

ReactPropTypes.number

ReactPropTypes.string

ReactPropTypes.oneOf([values])

The quest for the ideal React state management is one of the most discussed topics in the React community. If you look around, you will often come across the following question: How do I manage my state in React?

Especially devs who previously worked with other frameworks like Angular or Vue ask themselves how to manage their state in React. Often the question comes about an official solution for state management.

React Redux Cheat Sheet Example

Another question devs have been asking since the introduction of the Context API and Hooks API in React 16.8 is deciding between Redux or the Context API with useState/useReducer to manage its global state.

I would like to answer both questions in the following. For this purpose, I did some research in the community and got the opinion of many experienced React developers.

What is State Management?

Before we begin, however, I would like to clarify a few basic points. Before we can solve the question of the right state management, I think we need a definition of what exactly state management means.

The state describes the condition of an application at a given point in time.

Sub-types of the state are:

  • Server State,
  • navigation state
  • local UI state
  • global UI state

Accordingly, state management describes the maintenance of the state/knowledge of an application depending on all inputs.

Inputs usually take place on the server (API) or the client (user).

Accordingly, the difficulty of state management arises from the coordination of all subtypes of state in an application.

What does state mean in React?

The UI is the visual representation of the state of an application. As described above, State represents the state of an application at a given point in time.

It follows that: In React the State is a data structure that reflects the current state of the UI.

The State can consist of different kinds of data:

  1. A Boolean that decides whether a sidebar is open or not.
  2. The text content of a form.
  3. Server data pulled via an API.
Cheat

In JavaScript, we can represent this as follows:

All this data could be managed either locally (i.e. within a component using React hooks or setState) or globally.

In this case, managing means saving and changing the state, as well as displaying the state through the UI.

Is there an official / recommended state management solution like other frameworks in React?

Yes and no. With the setState method and the useState/useReducer hooks, there is a React-specific solution for local state management within a component. With this, you can already create reasonably complex apps.

There is no quasi-official solution for global state management like NgRx for Angular or Vuex for Vue. Here, you are spoiled for choice with React. Some solutions are specialized for certain parts of the application state (e.g. react-query), some are general solutions (e.g. Redux).

So how does one choose the appropriate state management solution?

I would like to deliberately leave Navigation-State out of this consideration. Any React application that has more than two views should rely on a routing library like react-router. From my point of view, handling the browser API is way too complex to manage it by yourself.

If we assume that the main difficulty is coordinating the subtypes, then the first thing we should ask ourselves is: what types of state do we need to manage in our (React) application? How complex is my state? How often does it change? And then we decide which solution is best for us.

Below you can see a diagram of my decision process.

Cheat

useState

The first question we ask is: Is our State shared by more than two components? If we answer in the negative, the question is: does our state have complex update logic, i.e. is the new state dependent on the old state or are multiple subvalues changed? If we also deny this, we use local state with useState.

For example, if we have a simple counter with one component, the use of local state with useState is sufficient.

When the Counter component is rendered for the first time, the useState hook is initialized with intialCount. As return value we get the state variable count and the update function setCount.

To change count, we need to call setCount with a new value. Whenever we call setCount, the counter component is re-rendered.

If we want to set the new value of count based on the old one, we should pass setCount a simple update function that passes the new value of count as its return value.

Exercises

  • Read about useState in the React docs.
  • Work through the useState guide

useReducer

Now, unlike our example above, if our state has complex update logic, it makes sense to useReducer.

As described above, complex in this context means that a change of the state must change many values of the state or that the state depends on the previous state.

First we define an initial state and a pure reducer function. This consumes a state and an action and returns a new state.

To use useReducer in our counter component, we proceed similarly as with useState: We initialize useReducer with initalState and reducer. After the initialization we get back the state and a dispatch function. The dispatch function is used to request a state change from the reducer. For this we call dispatch with an appropriate action.

Accordingly, the onClick handlers of the buttons no longer contain their own logic, but only request the state change via dispatch.

Exercises

  • Read about useReducer in the React docu

Context API + State hooks

If we look at the right part of the decision diagram, that is, if we answered yes to the question “Is the state shared by more than two components?”, we are faced with the question of whether our global state changes frequently? If we can answer this in the negative, the Context API can make our lives easier.

A typical example is the login state of a user. Which is needed in many different components.

In our code example, we initialize the context with createContext, which we make available to all children of the AuthProvider component.

With the custom hook useAuth, the child components can access the state. This allows us to save unnecessary prop drilling.

Tasks

  • Read more about React’s useContext hook in the React docs.
  • Read more about useContext combined with useState and useReducer

Server-State (react-query, Apollo, swr).

Looking at our decision diagram again, we see that we have used up React’s board resources. We are now moving into the area where it may be worthwhile to use external state management solutions.

If an application uses global state primarily to retrieve, cache, and update data residing on a server, it is recommended to use a specialized data management solution.

In an admin interface, we often need to display many different data in different views. Managing this data efficiently can be anything but trivial.

In the following, I would like to show a simple example using react-query.

Similar to our context API example, react-query provides us with a context provider and a custom hook.

With the custom hook useQuery we can now fetch the data we need. For this we pass useQuery a unique name and the actual fetch function. We get back the data (status, error, content) we need to display.

The real highlight is that react-query takes over the management for us. It makes sure that the data is cached and updated automatically. If we use the same query issues in a second component, react-query will not execute the query multiple times, but will fall back on the cached data.

In addition, the provided context provider is optimized to prevent unnecessary re-rendering of components. Implementing this functionality yourself is far from straightforward.

Tasks

  • Learn more about the motivation behind react-query
  • Learn about the alternatives Apollo and SWR
Redux

Redux et al.

But what do you do if the state is shared by multiple components, changes frequently, and is not mainly server state?

For example, to manage the state in a text editor with many buttons. This is where Redux comes in. Redux is very efficient, has a large ecosystem with many plugins (so-called middleware) and is very well documented.

React Cheat Sheet 2020

We reimplement our counter example here again using Redux and the Redux toolkit. It is very similar to the useReducer variant.

First, we initialize our state and our reducer. In our Counter component, we initialize a so-called selector; a function to select a subset of the state. Additionally, we use the useDispatch hook of Redux to be able to command state changes.

Unlike our useReducer variant, we do not need to name an action with a string. Action names are automatically generated by createSlice.

React Redux Cheat Sheet Printable

As our simple counter example shows, setting up Redux does require a bit more effort. So that since the official introduction of the Context API in React 16.3, it is mostly not worth the effort for small application.

The advantages of Redux over the combination of Context API and React hooks are:

React Redux Hooks

  • consistent and defined architectural patterns that can facilitate teamwork
  • easy debugging through the excellent browser extension
  • the use of different middleware
  • many add-ons and good extensibility
  • the cross-platform and cross-framework usage
  • depending on the app state, better performance than the Context API

While Redux is the best known and most popular state management solution for React, it is by no means the only one. Alternatives include: MobX, Recoil, RxJS.

Tasks

  • Learn more about using von Redux und Redux-Toolkit.
  • Research Redux alternatives
Redux

Conclusion

React Redux Form Example

It doesn’t always have to be Redux. Many React applications can get by without Redux. In many cases, using Redux adds unnecessary complexity.

React hooks and the Context API can cover many use cases that were previously solved with Redux

React Hooks Cheat Sheet

A specialized library is recommended for server-state caching.

The decision diagram can help developers find the right form of state management for their application.

React Native Cheat Sheet

Finally, the solutions shown are not mutually exclusive. There is nothing wrong with using local and global state in your application.

References
1n00b Q: Why would you ever use React w/o Hooks?
2State management in React?
3Is redux really a good idea?
Virdol, Martin – How To Simplify Your Application State Management
6Wieruch, Robin -React State Management
7Should I use a state management library like Redux or MobX?
8Erikon, Mark – When (and when not) to reach for Redux
9Dodds, Kent – Application State Managment with React
10Overview react-query
11Important Defaults – react-query
12On Cache Invalidation – Why is it hard?
13Erikson Marc – Blogged Answers: Redux – Not Dead Yet!