Skip to content

ReactJS

Posted on:September 23, 2022 at 03:22 PM

Prop vs state

How React works

What is a react component?

React and ReactDom

New way to run create-react-app

what create-react-app installs

import statement vs require statement

Difference between html and JSX

Three tenets of a component:

Props system

Rules for class based components:

Rules of state

What is useState function

CSS in React

JSX under the hood

Declarative vs Imperative

Container component

React state and working with events

When does the component should have a state

Passing data from child to parent (lifting the state up)

Two way binding

Shortcut for writing React component

Using JS in JSX code

Passing value via prop

Organising code

Adding event handlers to react components

Composition (Children props)

React state

React hooks

onChange Vs onInput for form input.

Multiple states in a component.

Updating state that depends upon previous State.

Adding two way binding for input fields in a form.

Child to parent data communication.

Lifting the state up

Controlled component

Presentational vs stateful component

Rendering conditional components

Styling React components

Conditional and dynamic styles

Debugging react apps

Compile time error:

Runtime error:

Wrappers and Fragments

Portals

Using Refs

useState vs useRef

Controlled vs Uncontrolled Components

Working with side effects

What is a side effect:

Managing more complex state with reducers

Manage app wide state with context

Effects reducers and context

useReducer Vs useState

React Context

Context limitations

Rules of using React hooks

Note: Ref prop is available in all built-in html components.

Forward Refs

React behind the scenes

Component update lifecycle(when props or state change)

  1. Get derived statefromprops().
  2. Shouldcomponentupdate (nextprops, nextstate). You can cancel the update process here.
  3. Render().
  4. Update child components.
  5. Getsnapshotbeforeupdate(prevprop, prevstate). Get scrolling position of user.
  6. Componentdidupdate().

React and ReactDOM

Preventing unneccesary Re-evaluations with React.memo()

// Memoising a sorted list, to save the compute time
// This will run only when items array change and not
// on every component evaluation.
const sortedList = useMemo(() => {
  return items.sort((a, b) => a - b);
}, [items]);

Class based components

Lifecycle methods:

Error boundary

Componentdidcatch()

Custom hooks

working with forms and user input

Note: ref prop works only on html elements?

using ref Vs state

Note: Event triggered when input loses focus is blur.

Formik : react library for working with forms.

Redux:

class Product extends Component {
  render() {
    return<H2>This is a heading<H2>;
  }
}

Redux

Redux Vs context Context is for low frequency state changes like login state etc.

Reducer function It is executed by redux library.

Receives two parameters, old state and action dispatched and return a new state object.

It is a pure function, same input values always produce same output. There should be no side effects is sending http request or read/write to local storage etc.

redux.createStore(reducer Fn)

store.subscribe(fn)

store.getState()
store.dispatch(action);
store.dispatch({type: 'increment'});

Redux code is placed in src/store folder. Create store and dispatcher function in a file here. Export store from this file.

In component file subscribe and dispatch to the provided store in appjs file. useSelector, useStore.

useDispatch(), returns a dispatcher function to dispatch actions to the store.

In appjs file import provider from react-redux. Wrap app component in provider component with store property. The store property is imported.

In the reducer function, always return a new state which will overwrite the previous state. Never mutate the state in the reducer function.

Redux toolkit

import {createSlice} from @reduxjs/toolk

Check the import statement for default export when splitting the code in slices.

Side effects, asyc functions and redux

Reducer function should be pure, side effect free and synchronous functions.

Where to put side effects and async code in redux.

Inside useEffect() in component or Inside custom action creators.

Fat reducers, components or action Coding choice.

Prefer reducers for synchronous side effect free code.

Prefer components or action creators for asynchronous code or code with side effects.

Action creators and think

Thunk A function that delays action until later.

Debugging redux toolkit based apps, use redux devtools chrome extension or install stand alone.

SPA apps

Client side routing. React router.

what is routing

React router Changes the URL in the browser based on user clicks but doesn’t send any request to the server or reload the page.

Install react router Dom.

Wrap the components in route component with path prop.

Wrap the app component with browserrouter.

Keep wrapped components in the page subfolder.

When we loads a new page the application state is lost.

Clicking on the links sends a request and loads the page.

Use link component in place of anchor tag from react router to prevent sending a request on clicking a link. Use to prop instead of href in this component.

Use navlink in navigation header instead of link. This will make them active if the page loaded is matching. For this we need to set the class/style for activeClassName prop.

For dynamic routes use colon : and useParams.

Switch component: only one of the children is shown.

Use exact prop to match the exact string in the URL.

Nested routes The route can be used in a nested manner, but path should follow the nested hierarchy.

Redirect Redirect component with to props.

Programmatic navigation. use history() hook.

history.push(): back button works. Add a page on history stack.

history.replace(): back button doesn’t work. Replace current page on history stack.

Query parameters don’t effect the route/path. Change query parameter using useHistory hook. Read query parameter using useLocation hook.

URLSearchParams(): Web api.

Note: Check if value returned from array find is a copy or reference.

How to publish react apps

Client side routing Vs server side routing.

Deployment steps:

lazy loading

Suspense component for fallback.

building code for Deployment

React spa is a static site. We need static site host for deployment.

Search for static website hosting provider.

Amazon S3, Firebase.

When hosting spa configure server to ignore the subpath and serve only index.html. ie rewrite all URLs to index.html.

React elements: Had, returned by react components. Class name can be applied.

React components: Returns single react element. Class name can’t be applied.

export default

import {Val [as value]} from './app'
import * as bundled from './app'

Inline styles: Scope is limited to the component. Hover effect is complex for inline CSS styles.

React app structure

Components “creation” lifecycle (only availaible in class based componenents)

  1. creation: constructor(props), added by ES6. Don’t cause sideefeects in this method. Initialize state.
  2. static getDerivedStateFromProps(props, state), Added in v16.3,
  3. render(): prepare and structure your jsx code, also renders child componenents
  4. ComponentDidMount(): can add http request

Components “update” lifecycle(only availaible in class based componenents)