</> Vikas Sharma

ReactJs reference notes

ReactJs reference notes


Introduction

ReactJs is an open-source javascript library for building User interfaces. It’s declarative, efficient and flexible.

Components

Functional Components

Simple javascript functions that return React elements (also the recommended way of writing Components). They don’t have state or lifecycle methods, but they can use hooks to add state and side effects.

const HelloComponent = (props) => {
	return <h1>Hello {props.name}</h1>;
};

Class Components

They offer more features such as state and lifecycle methods.

class CounterComponent extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			message: "Hello",
			count: 0,
		};
	}

	componentDidMount() {
		// runs after the component is mounted on the DOM
		console.log("Component did mount");
	}

	componentWillUnmount() {
		// runs before the component is about to unmount from the DOM
		console.log("Component will unmount");
	}

	handleClick() {
		this.setState({
			count: this.state.count + 1,
		});
	}

	render() {
		return (
			<div>
				<h1>{this.props.name}, current count: {this.state.count}</h1>
				<button onClick={this.handleClick}>Increment</button>
			</div>
		);
	}
}

JSX (JavaScript XML)

const element = <h1>Hello, React!</h1>;

Props

function MyComponent(props) {
	return <h1>{props.name}</h1>;
}

const App = () => {
	return <MyComponent name="John Doe" />;
};

State

class MyComponent extends React.Component {
  state = {
    count: 0,
  };

  handleClick = () => {
    this.setState({
      count: this.state.count + 1,
    });
  };

  render() {
    return (
      <div>
        <h1>{this.state.count}</h1>
        <button onClick={this.handleClick}>Increment</button>
      </div>
    );
  }
}

Hooks

React Hooks are functions that allow you to “hook into” React state and lifecycle features in function components. They provide a way to manage state and side-effects without using class components.

useState

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

useEffect

import React, { useState, useEffect } from 'react';

function Timer() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const intervalId = setInterval(() => {
      setSeconds(seconds + 1);
    }, 1000);

    return () => {
      clearInterval(intervalId);
    };
  }, [seconds]);

  return <p>Seconds: {seconds}</p>;
}

useContext

import React, { useContext } from 'react';

const MyContext = React.createContext();

function MyComponent() {
  const contextValue = useContext(MyContext);

  return <p>Context Value: {contextValue}</p>;
}

useReducer

import React, { useReducer } from 'react';

const initialState = { count: 0 };

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      return state;
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
    </div>
  );
}

useRef

import React, { useRef } from 'react';

function InputWithFocus() {
  const inputRef = useRef();

  const focusInput = () => {
    inputRef.current.focus();
  };

  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={focusInput}>Focus Input</button>
    </div>
  );
}

Custom Hooks

import { useState, useEffect } from 'react';

function useLocalStorage(key, initialValue) {
  const [value, setValue] = useState(() => {
    const storedValue = localStorage.getItem(key);
    return storedValue ? JSON.parse(storedValue) : initialValue;
  });

  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);

  return [value, setValue];
}

// Usage
function App() {
  const [name, setName] = useLocalStorage('name', 'Guest');

  return (
    <div>
      <p>Hello, {name}</p>
      <input
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
    </div>
  );
}

Rendering

ReactDOM.render(<Hello name="World" />, document.getElementById("root"));
function App() {
  return (
    <div>
      <Hello name="Alice" />
      <Hello name="Bob" />
      <Hello name="Charlie" />
    </div>
  );
}

Component Communication

Styling

Virtual DOM

Reconciliation

Reconciliation Process:

Keys in Reconciliation:

React Component Lifecycle

Mounting Phase

constructor()

render()

componentDidMount()

Updating Phase

static getDerivedStateFromProps()

shouldComponentUpdate()

render()

getSnapshotBeforeUpdate()

componentDidUpdate()

Unmounting Phase

componentWillUnmount()

Error Handling

componentDidCatch()

Note:

Code lab