React Study Guide Overview
After passing the review for the React phase of Flatiron’s Software Engineering Program, I thought it would be good to go over a few of the terms from the study guide and if there are any examples from the project, I’ll post them below.
What is the difference between props & state?
props (short for properties) are passed values, like strings and objects, into from a parent component to a child component. Props, which are JS objects, shouldn’t be changed during a component’s lifecycle.
State is created in a component and is used to keep track of info between rendering a component. State is mutable and is expected to change. Initial state, which is updated through React.Component’s .setState() because initial state should not be updated directly, is assigned in the constructor, which is the first function called upon the initialization of a component. A change in state can trigger a re-render of component. And just like props, they’re JS object.
// rrrumor-has-it-frontend/src/components/Home.js
class Home extends React.Component {
constructor() {
super();
// omitted code to save space
this.state = {
value: [],
componentValue: 0,
id: 0,
valueOfLikes: 0,
totalLikes:[],
};
}
What is the difference between functional & class components? When should you use which?
Functional components, which do not use React lifecycle methods like componentDidMount, are stateless and do not extend from React.Component. Props do not have a render method. They accept props as an argument & returns a React element. React-hooks can be used to convert class comps to functional comps.
// rrrumor-has-it-frontend/src/components/About.js
export default function aboutUs() {
return (
<div>
<div class=”about-section”>
<h1>About Us Page</h1>
<p class=”remove-margin”>We are a company that runs on rrrumours.</p>
</div> </div>
)
Class components use React lifecycle methods like, componentDidMount. They extend from React.Component and are stateful. Class components are required to have render(). Class components have access to the “.this” keyword. React-hooks can be used to convert class comps to functional comps.
// rrrumor-has-it-frontend/src/components/Home.js
class Home extends React.Component {
constructor() {
super();
// omitted code to save space
this.state = {
value: [],
componentValue:0,
id:0,
valueOfLikes:0,
totalLikes:[],
};
}
componentDidMount() {
this.props.getPosts();
}
// omitted code to save space
render() { // omitted code to save space }
What do the terms container (stateful) & presentational (stateless) mean?
Are these actually types of comps?
Container components are usually class components that are stateful. They can contain complex logic and rarely have any HTML markup of their own, aside from a wrapping <div>. Container components are also known to be smart as they can have external dependencies, like Redux.
// rrrumor-has-it-frontend/src/components/PostRumour.js
import React from ‘react’;
import ‘../stylesheet/view_post.css’;
import {connect} from ‘react-redux’;
import ‘../stylesheet/view_post.css’;
import {createPosts} from ‘../store/actions/postsAction’
class PostRumour extends React.Component {
constructor(props) {
super(props);
this.state = {
value: ‘Please Enter a Rumour’
};
this.handleChange = this.handleChange.bind(this);
this.createPostsFunction = this.createPostsFunction.bind(this);
}
Presentational components are typically stateless and have little logic. They can be converted to class component. Presentational components are also known to be dumb components as they have no dependencies on the rest of the app, apart from what is needs to exist.
// rrrumor-has-it-frontend/src/components/ContactUs.js
import React from ‘react’;
import ‘../stylesheet/about_us.css’;
export default function contactUs() {
return (
<div>
<div class=”about-section”>
<h1>Contact Us Page</h1>
<p class=”remove-margin”>Please Contact us:</p>
<p class=”remove-margin”>LinkedIn:</p>
<p class=”remove-margin”>https://www.linkedin.com/in/josh-raiborde-6aa3bb15/ </p>
</div> </div> )}
Container and Presentational components are not actual types of comps but a way on how to organize a React application.
What is the difference between mapStateToProps & mapDispatchToProps?
mapStateToProps() is a utility which helps your comp get updated state. It’s the first argument passed in connect() and is called every time the store state changes. In mapStateToProps() we specify exactly which slice of the state we want to provide to a component.
class PostRumour extends React.Component {
// omitted code to save space
}
const mapStateToProps = (state) => ({users:state.users})
export default connect(mapStateToProps, {createPosts})(PostRumour)
mapDispatchToProps() is a utility which will help components to fire an action event, dispatching action which may cause change of app state. It’s the second argument in connect() and allows actions to be combined with dispatch & connect events on the page to actions in the store.
What are the common lifecycle methods and in what order do they get invoked?
When does componentDidMount get executed?
The common lifecycles methods are Mounting, Updating and Unmounting. The componentDidMount is called after render is executed.
· Mounting > constructor > render> react updates DOM and refs > componentDidMount
· Updating > (new props, .setsState(), forceUpdate() ) render> react updates DOM and refs > componentDidMount
· Unmounting > componentWillUnmount
What’s the difference between client-side & server-side routing?
Client-side routing happens when the route is handled internally by the JS that is loaded on the page. When a user clicks on a link, the URL changes but the request to the server is prevented. The adjustment to the URL will result in a changed state of the app. The changed state will result in a different view of the webpage. Routing between views is usually faster because less data is processed. Transitions & animations between views are easier to implement. Longer initial load time on first request for full web sites/apps. It is not standard & requires more setup or a library to work. Search engine crawling is less optimized.
Server-side routing will only request the data that’s needed, no more/less. Because SS routing has been the standard for a long time, search engines are optimized for webpages that come from the server. Every request is a full-page refresh, needless data is being requested. It can take a while for the page to be rendered, but only when the document to be rendered is large or when you have slow internet speed.
How does client-side routing work?
What comps do we use from the react-router library to set up client-side routing?
React renders the appropriate info on the DOM using its comp structure. CS routing helps to maintain a seamless UX in a typical SPA.
The React Router library makes this possible.
The Router Module include <BrowserRouter/> , <Switch/>, & <Route/>.
Everything inside the <BrowserRouter/> comp indicates info about Routing. It’s a wrapper comp for all the comps that will be using CS routing to render themselves & it informs React about that.
The <Switch/> comp ensures only one route is handled at a time.
The <Route/> comp tells us which comp will be rendered on which route.
The Exact property ensures that the comp is rendered only when the route matches the exact string mentioned in the path & no substring or superstring of that route will be able to render that comp.
Nesting routes enables us to build single-page applications in React that behave like they have many pages.
// rrrumor-has-it-frontend/src/App.js
// omitted code to save space
function App() {
return (
<BrowserRouter>
<nav>
<div className=”menu-icon”> <span className=”fas fa-bars”></span></div>
<div className=”logo”>Rumour Has It . . .</div>
<div class=”nav-items”>
<li><Link to=”/home”>Home</Link></li>
<li><Link to=”/post/rumour”>Post Rumour</Link></li>
<li><Link to=”/about/us”>About us</Link></li>
<li><Link to=”/contact/us”>Contact us</Link></li>
</div>
</nav>
<Route exact path=”/” component={Splash}/>
<Switch>
<Route path=”/home” render={(props) => <Home {…props} key={Date.now()}/>}></Route>
<Route path=”/post/rumour”><PostRumour/></Route>
<Route path=”/comments”><Comments/></Route>
<Route path=”/about/us”><About/></Route>
<Route path=”/contact/us”><Contact/></Route>
</Switch>
<Footer/>
</BrowserRouter>
)}
export default App;
What is Redux? Why would we use it?
Redux is a predictable state container designed to help create consistency across client, server, and native environments. The state of an app is kept in a store, each comp can access any state that it needs. It is Accessible through the <provider/>, using connect. When something changes, a new object is created (using actions & reducers)
* rrrumor-has-it-frontend/src/index.js
* rrrumor-has-it-frontend/src/comps/Home.js
How do we set up redux? What comps/functions do we use from the redux library?
It is imported, then create a Reducer, create a Redux Store, wrap the App comp in <Provider>, create & Connect a Container Comp.
// rrrumor-has-it-frontend/src/store/store.js
import {createStore, applyMiddleware} from ‘redux’
import thunk from ‘redux-thunk’
import {composeWithDevTools} from ‘redux-devtools-extension’
import rootReducer from ‘./reducers’
const initalState = {}
const middleware = [thunk]
const store = createStore(rootReducer, initalState, composeWithDevTools(applyMiddleware(…middleware)))
export default store;
// rrrumor-has-it-frontend/Index.js
import React from ‘react’;
import ReactDOM from ‘react-dom’;
import ‘./index.css’;
import App from ‘./App’;
import store from ‘./store/store’
import {Provider} from ‘react-redux’;
import reportWebVitals from ‘./reportWebVitals’;
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById(‘root’)
);
We use connect, provider, createStore, applyMiddleware, Thunk, etc.
How do we give comps access to the redux store?
Use connect & provider.
The <Provider> comp makes the store available to other React comps.
Use the connect function from React Redux, and supply a mapStateToProps function that pulls out the data you need.
How do you update state in a pure React app (no redux)? How do you update the store of a react/redux app?
.setState updates state.
Action creators & actions update store.
What is redux thunk middleware? When & why would we need it?
Thunk allows us to return a function inside of our action creator instead of a JS object. That returned function receives the store’s dispatch function and with that we are able to dispatch multiple actions: one to place the state in a loading state, & another to update our store with the returned data
* It makes some actions asynchronous & it works with redux.
What is State Management?
It facilitates communication & sharing of data across comps.
What is the store?
It is where state is stored. The Redux store brings together the state, actions, & reducers that make up the app.
What is a reducer?
A reducer takes a state & an action & reduces it into a new state. You can use multiple reducers & then use combineReducers
rrrumor-has-it-frontend/src/store/reducers/index.js
rrrumor-has-it-frontend/src/store/reducers/singleReducer.js
rrrumor-has-it-frontend/src/store/reducers/usersReducer.js
What is an action creator?
An action creator is a plain function that returns a JS object with type & payload, which is an action object.
What is an action?
Events that occur in the app based on user input & trigger updates in the state. Actions are plain JS objects that have a type field. Actions must be created to update state. Any comp connected can update state using defined action. The action, with the previous state, produces an updated state.
What is the purpose of the Provider?
Gives access to the redux store to anything wrapped in a connect(). Provider, imported from react-redux, avoids passing store as a prop. It alerts the Redux app when there has been a change in state. It will re-render the React app. It wraps around our App comp. All comps shouldn’t be re-rendered every time there’s a change in state, so connect() will specify the changes to the store’s state to prompt a re-render of the app. The connect(), allows us to specify which data we are listening to (through mapStateToProps), & which comp we are providing the data.
What’s the purpose of the connect function & what are the arguments that it expects?
The connect() function connects a React comp to a Redux store.
It provides its connected comp with the pieces of the data it needs from the store & the functions it can use to dispatch actions to the store. It does not modify the comp class passed to it; instead, it returns a new, connected comp class that wraps the comp you passed in. The connect function takes two arguments, both optional: mapStateToProps: called every time the store state changes. It receives the entire store state, & should return an object of data this comp needs. mapDispatchToProps: this parameter can either be a function, or an object.
These are just a few questions from the study guide.
I’m really thankful that I got to attend Flatiron’s online bootcamp for Software Engineering. I’ve learned a lot and I look forward to continue to learn in this field.