Skip to content

Instantly share code, notes, and snippets.

@Buggytheclown
Last active November 16, 2022 15:55
Show Gist options
  • Save Buggytheclown/e2ce9f1b8c72400d15ae54d1d2e41f41 to your computer and use it in GitHub Desktop.
Save Buggytheclown/e2ce9f1b8c72400d15ae54d1d2e41f41 to your computer and use it in GitHub Desktop.

https://stackblitz.com/edit/rs-react-interview-vector-cp-mj19y8

import React, { useState, useEffect, useRef, useContext } from "react"; import "./style.css";

function range(x) { return Array.from({ length: x }, (_, ind) => ind); }

// 1) Is it possible to use React without JSX? // 2) What is the virtual DOM? How does react use the virtual DOM to render the UI?

// *** // 9) How not to render on props change? const HeavyComponent = React.memo(({ data, onClick }) => { console.log("HeavyComponent: render"); return HeavyComponent: {data}; });

const Instance = ({ ind }) => { // 5.1) What is the component lifecycle? useEffect(() => { console.log(Instance(${ind}): created); return () => { console.log(Instance(${ind}): destroyed); }; }, []);

return

Instance: {ind}
; };

const CounterContext = React.createContext(100);

// 7) When is a component rendered? Which component will be rerendere after SideCounter click? const ComponentB = ({ data }) => { console.log("ComponentB: render"); // 8) What is the difference between the context API and prop drilling? // 10) Redux data flow? const value = useContext(CounterContext); return ( drilled: {data}; context: {value} ); };

const ComponentA = React.memo(props => { console.log("ComponentA: render"); return <ComponentB {...props} />; });

const SideCounter = () => { const [count, setCount] = useState(0); return (

SideCounter: {count} <button onClick={() => setCount(x => x + 1)}>+
); };

export default function App() { const [count, setCount] = useState(0); const [data, setData] = useState("someData"); const refCount = useRef(0); const [drilled, setDrilled] = useState(0); const [context, setContext] = useState(100);

useEffect(() => { console.log(refCount.current is ${refCount.current}); // 5.2) What is the difference between refs and state variables? }, [refCount.current]);

return (

refCount: {refCount.current} <button onClick={() => { // 3) What is the difference between refs and state variables? refCount.current += 1; }} > +
count: {count} <button onClick={() => setCount(x => x + 1)}>+
{/* 4) Is it OK to use arrow functions in render methods? */} <HeavyComponent data={data} onClick={() => setData(data + "!")} />
{range(3).map(el => ( // 6) Is it a good idea to use Math.random for keys? ))}
<CounterContext.Provider value={context}> </CounterContext.Provider> <button onClick={() => setDrilled(x => x + 1)}>drill+ <button onClick={() => setContext(x => x + 1)}>context+
); }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment