WEB
JS
DIGITALIZE
FRONTEND
REACTJS
Each component has several lifecycle methods that you can override to run code at particular times in the process.
Mounting
Mounting means putting elements into the DOM.
React has four built-in methods that gets called, in this order, when mounting a component:
The render() method is required and will always be called, the others are optional and will be called if you define them.
Example:
A component is updated whenever there is a change in the component's state or props.
React has five built-in methods that gets called, in this order, when a component is updated:
1. getDerivedStateFromProps()
2. shouldComponentUpdate()
3. render()
4. getSnapshotBeforeUpdate()
5. componentDidUpdate()
The render() method is required and will always be called, the others are optional and will be called if you define them.
React has only one built-in method that gets called when a component is unmounted:
Hooks are the new feature introduced in the React 16.8 version. It allows you to use state and other React features without writing a class. Hooks are the functions which "hook into" React state and lifecycle features from function components. It does not work inside classes.
We can simply imagine as it the migration from class component to functional and make the latest one to be used as statefull component with additional capabilities and features.
There is no constructor function and instead of that we can use useState() function inside the function component to create and manage states of the component.
Example:
The Effect Hook allows us to perform side effects (an action) in the function components. It does not use components lifecycle methods which are available in class components. In other words, Effects Hooks are equivalent to componentDidMount(), componentDidUpdate(), and componentWillUnmount() lifecycle methods.
Side effects have common features which the most web applications need to perform, such as:
Example:
Others important built-in hooks:
useContext
useReducer
useCallback
useMemo
useRef
SPA stands for Single Page Application. It is a very common way of programming websites these days. The idea is that the website loads all the HTML/JS the first time you visit. When you then navigate, the browser will only rerender the content without refreshing the website.
In traditional websites, the browser requests a document from a web server, downloads and evaluates CSS and JavaScript assets, and renders the HTML sent from the server. When the user clicks a link, it starts the process all over again for a new page.
Client side routing allows your app to update the URL from a link click without making another request for another document from the server. Instead, your app can immediately render some new UI and make data requests with fetch to update the page with new information.
React-router-dom package enables faster user experiences because the browser doesn't need to request an entirely new document or re-evaluate CSS and JavaScript assets for the next page. It also enables more dynamic user experiences with things like animation.
Visualization:
https://remix.run/_docs/routing
Let's a odd react-router to our application clinic
npm i react-router-dom
index.js
:We want the patients, history pages to render inside of the <App> layout. so we need layout components that will stay shown in each nested component, for example 'Sidebar'.
layout
at pages/layout.js
:to define our pages, we have to create routes array and pass it to the createBrowserRouter
, each object of this array at least must have the following properties:
path
, element
.
History
, Patients
at src/pages/
:patients
history
Now run the application should start and you can navigate from page to another inside the layout.
NavLink
to fix this.as you see, we use this pattern /:id
, colon to inform the router that there will be a parameter passing that destination page have to receive.
pages/patient.js
to access passed parameter via URL, we can use useParams
hooks function.
Now we can test our new changes and it should work as expected.
Component composition is the name for passing components as props to other components, thus creating new components with other components.
Example:
Define Button component:
Use Button Component as wrapper for other children:
Composition help us to solve prop drilling problem and enhance the performance.
Prop Drilliing:
Prop drilling is the act of passing props through multiple layers of components.
Context provides a way to pass data through the component tree without having to pass props down manually at every level.
In a typical React application, data is passed top-down (parent to child) via props, but such usage can be cumbersome for certain types of props (e.g. locale preference, UI theme) that are required by many components within an application. Context provides a way to share values like these between components without having to explicitly pass a prop through every level of the tree.
Example:
Pass theme mode as props through 3 layers so ButtonThemed can use it
Using context, we can avoid passing props through intermediate elements:
React.createContext
const MyContext = React.createContext(defaultValue);
Context.Provider
<MyContext.Provider value={/* some value */}>
Every Context object comes with a Provider React component that allows consuming components to subscribe to context changes.
The Provider component accepts a value prop to be passed to consuming components that are descendants of this Provider. One Provider can be connected to many consumers. Providers can be nested to override values deeper within the tree.
All consumers that are descendants of a Provider will re-render whenever the Provider’s value prop changes.
Context.Consumer
Children components (subscribed) act as consumer, to access context provided by the provider:
Class Component
Function Component:
Let's add functionality of Theme switching using Context API.
contexts
ThemeContext.js
Access context from the consumers components:
Now apply the context provider:
Now you can print the context object at your console to see that consumers access the values provided from the provider and shared easily without passing props from parent to deep child.
But what if we want to manage the state with the provider? let's optimize the the code design:
let's create a state themeValue
inside the provider:
Wrap our application with provider:
Now we can still access the state inside any child component like patients.js
:
Good!, Let's add new component to toggle the theme and apply some css on the component so we can see how our application will work:\
First let's apply some css on the components:
components
directory and create a new file called sidebar.jsx
App.css
Layout.js
react-switch
, to make our practicing easy:create switcher.jsx
component at components
and add the following:
As you see displayed value changable depends on selected theme, also to toggle switch component we have to manage a boolean state value.
Let's (add states, edit THEMES object, define call back action for switch change event, and expose all these to consumers) to the ThemeProvider context so our switch component can access:
onSwitcherChange
listen to change event on switch component and update the state so render function rendering again with new values passing to the consumers.
Also let's change background color of the header and sidebar, so they are changing depends on selected theme:
sidebar.jsx
:
layout.jsx
Now as you see, you can toggle the theme from the switch and sidebar and header background will change according to the updates on provider state.
Tailwind CSS, as per their own website is a "utility-first CSS framework" which provides several of these opinionated, single-purpose utility classes that you can use directly inside your markup to design an element.
It is prefer to follow their official steps:
https://tailwindcss.com/docs/guides/create-react-app
Help:
postcss src/App.css -o public/output.css
to the script in package.json file:and in the public/index.html
, link output.css:
https://reactrouter.com/
https://tailwindcss.com/
https://reactjs.org/docs/
https://www.npmjs.com/package/react-switch